Testing and Error Handling Intro to Java. Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code,

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
When you use an input or output file that does not exist, what will happen? −The compiler insists that we tell it what the program should do in such case.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions CIS 304 Intermediate Java Programming for Business.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Introduction to Computer Programming Error Handling.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Java Software Solutions Foundations of Program Design Sixth Edition
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Creating a GUI Class An example of class design using inheritance and interfaces.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Chapter 8-Exception Handling/ Robust Programming.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Question of the Day completes starts  What word completes the 1 st word & starts the 2 nd one: DON???CAR.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Exceptions Chapter 9.
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Week 14 - Wednesday CS 121.
Creating and Modifying Text part 2
CSE 501N Fall ’09 17: Exception Handling
Exceptions 10-Nov-18.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling.
Web Design & Development Lecture 7
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
Go to pollev.com/cse143.
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Programming: From Problem Analysis to Program Design, 4e
Throwing, Catching Defining
Presentation transcript:

Testing and Error Handling Intro to Java

Testing We test to try and make sure our programs work correctly and have no bugs If we have access to the code, we look at the structure of the code and try to make sure every case is tested. This is called “white box testing” Otherwise, we test the code seeing if it does its job and if what it does matches the Javadocs. This is called “black box testing”

Testing Example public class TestExample { private int[] array = new int[4]; private int size = 0; // adds a number to the array, // resizes if necessary public void add(int num) { if (this.size == this.array.length) this.resize(); this.array[size++] = num; } private void resize() { int[] temp = new int[this.array.length * 2]; for (int i = 0; i < this.array.length; i++) temp[i] = this.array[i]; this.array = temp; } White box testing: we can see the code (we can only directly call the add() method). What would you test? Add a number, make sure it’s there Add at least 5 numbers to make sure the array resizes

Testing Example public class TestExample { private int[] array = new int[4]; private int size = 0; // adds a number to the array, // resizes if necessary public void add(int num) { if (this.size == this.array.length) this.resize(); this.array[size++] = num; } private void resize() { int[] temp = new int[this.array.length * 2]; for (int i = 0; i < this.array.length; i++) temp[i] = this.array[i]; this.array = temp; } Black box testing. We can only see the add() method exists and the Javadocs What would you test? Add a number, make sure it’s there Add a bunch of numbers and make sure they are all there We don’t know what value the array first resizes, so we have to add a bunch to hope we hit the case when it does resize

Boundary Cases You should always test the boundary cases, the ones that are on the border Test -2, -1, 4, 5, 6 – numbers that are edge cases Always test valid and invalid numbers if (-2 < a && a <= 5) …

More Testing Regression testing: if you update/add code, make sure what worked before still works Unit testing: individually test each method with its own mini driver program. Typically used with white box testing Good practice to write code and unit tests at the same time

Testing Data Where does the data come from? You can make up values that you think the problem should have trouble with (invalid cases) You can write programs to randomly generate a lot of data. This is helpful for blackbox testing. Example: you write a program that adds 1,000,000 random Pokemon to a trainer and make sure that it doesn’t crash

Error Handling How do we handle errors in programming? What is an error? NullPointerException, FileNotFoundException, IllegalArgumentException, etc. Display error message with System.err.println() Quit the program with System.exit(1) Both of these are really ugly – can we do better?

Exception Handling What is an Exception? An Object which contains information about the error that just happened You’ve seen a lot of these. You can even subclass them to create your own! How does this help us? First, let’s talk about the Call Stack Exception e1 = new Exception(); Exception e2 = new NullPointerException(); Exception e3 = new InputMismatchException();

Call Stack The Call Stack in Java shows you the path through the program the computer took to reach where it is Keep a stack (like a stack of plates) of all of the methods you call. Once you enter a new method, you put that on top of the stack. If you exit a method, remove it from the stack

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA methodB

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA methodB

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodA

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main methodC

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack main

Stack Example public static void main(String[] args) { System.out.println(“starting”); methodA(); methodC(); } private static void methodA() { System.out.println(“Starting A”); methodB(); System.out.println(“done A”); } private static void methodB() { System.out.println(“Starting B”); System.out.println(“Done B); } private static void methodC() { System.out.println(“Starting and ending C”); } Call Stack

How do you read this? Bottom up The main method called methodA on line 12 methodA called methodB on line 17 methodB called methodC on line 22 methodC had an error on line 27

Back to Exceptions So how do you actually create an exception? Since it’s an Object, you use the new keyword The keyword for exceptions is throw public double mySqrt(double num) { if (num < 0) throw new IllegalArgumentException(“The value of num must be non-negative”); return Math.sqrt(num); } If this happens, the method stops executing right here and returns to the method that called it This is the Java way to say “Something went wrong. I don’t know how to deal with it, make someone else fix it”

Try Blocks Now what? We handle exceptions with what’s called a try block try { Scanner scanner = new Scanner(new FileReader(“file.txt”)); // do something here } catch (IOException e) { e.printStackTrace(); } Inside the try, you put the code that might “throw” (or cause) an exception Now you don’t have to write “throws IOException” at the top! You can think of the code saying: “Do this code. If this exception is caused, stop executing, and execute this code instead.” We are declaring an IOException object called e here. Java will assign the value of e for us. Since e is as object, we can call methods on it. Somewhere in the constructor for FileReader defined by Java, they wrote “throw new IOException()”

Throwing Exceptions If a method could potentially throw an Exception, you have two choices: Handle it with a try-catch block Declare that the method which calls it could also throw that same exception public static void main(String[] args) { try { System.out.println(mySqrt(-4)); } catch (IllegalArgumentException e) { System.out.println(“Oops!”); } Potentially throws an IllegalArgumentException public static void main(String[] args) throws IllegalArgumentException { System.out.println(mySqrt(-4)); } Here, your program ends gracefully Here, your program crashes!

Example public static void main(String[] args) throws IOException { Scanner kb = new Scanner(System.in); char choice; do { choice = kb.next().charAt(0); switch (choice) { choice ‘a’: Scanner scanner = new Scanner(new FileReader(kb.nextLine())); // do something with the scanner break; } } while (choice != ‘q’); } Before If the file does not exist, this is going to cause a FileNotFoundException Program would crash!

Example public static void main(String[] args) { Scanner kb = new Scanner(System.in); char choice; do { choice = kb.next().charAt(0); switch (choice) { choice ‘a’: try { Scanner scanner = new Scanner(new FileReader(kb.nextLine())); // do something with the scanner } catch (FileNotFoundException e) { System.out.println(“File could not be found”); } break; } } while (choice != ‘q’); } After If the file does not exist, a FileNotFoundException is thrown, but it is “caught” with our catch block The scanner code stops execution, it displays “File could not be found” and continues. It does NOT crash

Exceptions and the Call Stack What actually happens when we throw an Exception? Call Stack main createDatabase createTable readInputFile readInputFile tries to read a file. If it handles the exception (it uses a try-catch block), then we don’t have to do anything else. If it does not handle the exception, it must declare that it “throws IOException” public void readInputFile(String filename) throws IOException { Scanner scanner = new Scanner( new FileReader(filename)); // read in and do something with the data } public void readInputFile(String filename) { try { Scanner scanner = new Scanner( new FileReader(filename)); // read in and do something with the data } catch (IOException e) { // deal with the exception here } We’re saying watch out, we might run into this problem and I don’t want to deal with it. We’re saying I know this issue might happen and I’m going to take care of it if it does. This won’t compile unless you do one of these two options.

Exceptions and the Call Stack Let’s say readInputFile didn’t handle the exception That means createTable must either handle it with a try-catch block OR it can make someone else handle it Call Stack main createDatabase createTable readInputFile throws IOException public void createTable() throws IOException { String filename = “file.txt”; readInputFile(filename); } Since readInputFile could throw an IOException, we must handle it or say that createTable could also throw the exception Let’s just say that createTable also does not handle it

Exceptions and the Call Stack The error keeps getting thrown up the Call Stack until someone deals with it If we keep throwing it and it’s not handled in main, then the program crashes Call Stack main createDatabase createTable throws IOException readInputFile throws IOException We don’t want the program to crash, so we’re going to handle the Exception in createDatabase public void createDatabase() { try { createTable(); } catch (IOException e) { System.out.println(“Error”); } Now if the IOException is thrown in readInputFile, the code stops executing in readInputFile and createTable, and it goes to the catch block here Not being able to find the file in readInputFile will now be unable to make our program crash.

Creating Our Own Exceptions What if you need to have an error that isn’t really the same as any of the built in Java ones? We can create our own! Just extend the Exception Object We can now say “throw new EvenNumberRequiredException()” public class EvenNumberRequiredException extends Exception { public EvenNumberRequiredException() { super(“An even number is required”); }

What about Multiple Exceptions Some methods could potentially throw more than one Exception So create more than 1 catch block You can only go into 1 catch block, then you keep executing code try { crazyMethod(); } catch (IOException e) { // do something } catch (NullPointerExecption e) { // do something } …

What about Multiple Exceptions What happens with inheritance here? If you look at the Exception hierarchy: Exception IOException FileNotFoundException Is a try { crazyMethod(); } catch (IOException e) { // do something } catch (FileNotFoundException e) { // do something } … A FileNotFoundExcetpion is an IOException, so which catch block get executed? Always the first one! Here, the FileNotFound catch block will NEVER be executed

What about Multiple Exceptions What happens with inheritance here? If you look at the Exception hierarchy: Exception IOException FileNotFoundException Is a try { crazyMethod(); } catch (FileNotFoundException e) { // do something } catch (IOException e) { // do something } … Now if a FileNotFoundException is thrown, it will execute the FileNotFound catch block and skip the IOException block.

What about Multiple Exceptions If you want to catch every possible Exception with 1 catch block, catch Exception try { badMethod(); } catch (Exception e) { // do something }

Checked versus Unchecked Checked exceptions must be handled or declared that they are thrown IOException, FileNotFoundException, etc. Unchecked exceptions can be handled, but you don’t need to declare that they are thrown NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions all extend RuntimeException

Finally Block A finally block will be executed after the try no matter how the try block is exited PrintWriter writer = null; String filename = kb.nextLine(); try { writer = new PrintWriter(new FileWriter(filename)); // write something to the file } catch (IOException e) { System.err.println(“Problem writing to “ + filename); } finally { if (writer != null) writer.close(); }

Summary Exceptions are a way of error handling in Java If a method could cause an exception, it must either handle it with a try-catch block or it has to declare that it throws that exception If it declares it will throw the exception, every method which calls it must handle it or throw it. This repeats (recursively!) until main. If main throws it, the program crashes.