Exception Handling Lecture Objectives To learn how to

  • Slides: 43
Download presentation
Exception Handling

Exception Handling

Lecture Objectives • To learn how to throw exceptions • To be able to

Lecture Objectives • To learn how to throw exceptions • To be able to design your own exception classes • To understand the difference between checked and unchecked exceptions • To learn how to catch exceptions • To know when and where to catch an exception

The finally clause • Exception terminates current method • Danger: Can skip over essential

The finally clause • Exception terminates current method • Danger: Can skip over essential code Example: reader = new File. Reader(filename); Scanner in = new Scanner(reader); read. Data(in); reader. close(); // May never get here

The finally clause (Cont’d) • Must execute reader. close() even if exception happens •

The finally clause (Cont’d) • Must execute reader. close() even if exception happens • Use finally clause for code that must be executed "no matter what"

The finally clause (Cont’d) File. Reader reader = new File. Reader(filename); try { Scanner

The finally clause (Cont’d) File. Reader reader = new File. Reader(filename); try { Scanner in = new Scanner(reader); read. Data(in); } finally { reader. close(); // if an exception occurs, finally clause // is also executed before exception is // passed to its handler }

The finally clause (Cont’d) • Executed when try block is exited in any of

The finally clause (Cont’d) • Executed when try block is exited in any of three ways: § After last statement of try block § After last statement of catch clause, if this try block caught an exception § When an exception was thrown in try block and not caught • Recommendation: don't mix catch and finally clauses in same try block

Syntax: The finally clause Try { statement . . . } finally { statement

Syntax: The finally clause Try { statement . . . } finally { statement . . . }

Syntax: The finally clause (Cont’d) Example: File. Reader reader = new File. Reader(filename); try

Syntax: The finally clause (Cont’d) Example: File. Reader reader = new File. Reader(filename); try { read. Data(reader); } finally { reader. close(); } Purpose: To ensure that the statements in the finally clause are executed whether or not the statements in the try block throw an exception.

Designing Your Own Execution Types • You can design your own exception types– subclasses

Designing Your Own Execution Types • You can design your own exception types– subclasses of Exception or Runtime. Exception if (amount > balance) { throw new Insufficient. Funds. Exception( "withdrawal of " + amount + " exceeds balance of “ + balance); } • Make it an unchecked exception–programmer could have avoided it by calling the method get. Balance() first Continued…

Designing Your Own Execution Types (Cont’d) • Make it an unchecked exception–programmer could have

Designing Your Own Execution Types (Cont’d) • Make it an unchecked exception–programmer could have avoided it by calling get. Balance first • Extend Runtime. Exception or one of its subclasses • Supply two constructors 1. Default constructor 2. A constructor that accepts a message string describing reason for exception

Designing Your Own Execution Types (Cont’d) public class Insufficient. Funds. Exception extends Runtime. Exception{

Designing Your Own Execution Types (Cont’d) public class Insufficient. Funds. Exception extends Runtime. Exception{ public Insufficient. Funds. Exception() { } public Insufficient. Funds. Exception(String message) { super(message); } }

The Method print. Stack. Trace() • Used to determine the order in which the

The Method print. Stack. Trace() • Used to determine the order in which the methods were called and where the exception was handled

The Method print. Stack. Trace() (Cont’d) import java. io. *; public class Print. Stack.

The Method print. Stack. Trace() (Cont’d) import java. io. *; public class Print. Stack. Trace. Example 1 { public static void main(String[] args) { try { method. A(); } catch (Exception e) { System. out. println(e. to. String() + " caught in main"); e. print. Stack. Trace(); } } Continued…

The Method print. Stack. Trace() (Cont’d) public static void method. A() throws Exception {

The Method print. Stack. Trace() (Cont’d) public static void method. A() throws Exception { method. B(); } public static void method. B() throws Exception { method. C(); } public static void method. C() throws Exception { throw new Exception("Exception generated " + "in method C"); } } Continued…

The Method print. Stack. Trace() (Cont’d) • Sample Run: java. lang. Exception: Exception generated

The Method print. Stack. Trace() (Cont’d) • Sample Run: java. lang. Exception: Exception generated in method C caught in main java. lang. Exception: Exception generated in method C at Print. Stack. Trace. Example 1. method. C (Print. Stack. Trace. Example 1. java: 30) at Print. Stack. Trace. Example 1. method. B (Print. Stack. Trace. Example 1. java: 25) at Print. Stack. Trace. Example 1. method. A (Print. Stack. Trace. Example 1. java: 20) at Print. Stack. Trace. Example 1. main (Print. Stack. Trace. Example 1. java: 9)

Effective Design • Unfixable Error: If possible, it’s better to terminate the program abnormally

Effective Design • Unfixable Error: If possible, it’s better to terminate the program abnormally than to allow the error to propagate. • Normal versus Exceptional Code: The exception handler --- the catch block --- is distinct from the (normal) code that throws the exception --- the try block. • Using an Exception: If your exception handler is not significantly different from Java’s, let Java handle it.

Effective Design (Cont’d) • Handling Exceptions. § Report the exception and terminate the program;

Effective Design (Cont’d) • Handling Exceptions. § Report the exception and terminate the program; § Fix the exceptional condition and resume normal execution. § Report the exception to a log and resume execution. • Program Development. Exceptions help identify design flaws during program development. • Report and Resume. Failsafe programs should report the exception and resume.

Effective Design (Cont’d) • Defensive Design. Anticipate potential problems, especially potential input problems. •

Effective Design (Cont’d) • Defensive Design. Anticipate potential problems, especially potential input problems. • Fixing an Exception. Handle fixable exceptions locally. This is both clearer and more efficient. • Library Exception Handling. Many library classes leave exception handling to the application. • Truly Exceptional Conditions. Use exceptions to handle truly exceptional conditions, not for expected conditions.

Summary of Important Points • In Java, when an error occurs, you throw an

Summary of Important Points • In Java, when an error occurs, you throw an Exception which is caught by exception handler code. A throw statement --- throw new Exception() --- is used to throw an exception. • A try block is contains one or more statements that may throw an exception. Embedding a statement in a try block indicates your awareness that it might throw an exception and your intention to handle the exception.

Summary of Important Points (Cont’d) • Checked exceptions must be caught or declared by

Summary of Important Points (Cont’d) • Checked exceptions must be caught or declared by the method in which they occur. • Unchecked exceptions (subclasses of Runtime. Exception) are handled by Java if they are not caught in the program. • A catch block contains statements that handle the exception that matches its parameter. • A catch block can only follow a try block. • There may be more than one catch block for each try block.

Summary of Important Points (Cont’d) • The try/catch syntax separates the normal parts of

Summary of Important Points (Cont’d) • The try/catch syntax separates the normal parts of an algorithm from special exceptional handling code. • A method stack trace is a trace of a program’s method calls -Exception. print. Stack. Trace(). • Static scoping: how the program is written. Depends on declarations and definitions. • Dynamic scoping: how the program is executed. Depends on method calls.

Summary of Important Points (Cont’d) • Finding a Catch Block: Search upward through the

Summary of Important Points (Cont’d) • Finding a Catch Block: Search upward through the static scope, and backward through the dynamic scope. • The Java Virtual Machine handles unchecked exceptions not caught by the program. • Many Java library methods throw exceptions when an error occurs. • Example: Java's integer division operator will throw an Arithmetic. Exception if an attempt is made to divide by zero.

Summary of Important Points (Cont’d) • Four ways to handle an exception: § Let

Summary of Important Points (Cont’d) • Four ways to handle an exception: § Let Java handle it. § Fix the problem and resume the program. § Report the problem and resume the program. § Print an error message and terminate. • The (optional) finally block contains code that will be executed whether an exception is raised or not. • Exceptions should be used for exception truly exceptional conditions, not for normal program control. • User-defined exceptions can extend the Exception class or one of its subclasses.

A Complete Program • Program: § § § Asks user for name of file

A Complete Program • Program: § § § Asks user for name of file File expected to contain data values First line of file contains total number of values Remaining lines contain the data Typical input file: 3 1. 45 -2. 1 0. 05

A Complete Program (Cont’d) • What can go wrong? § File might not exist

A Complete Program (Cont’d) • What can go wrong? § File might not exist § File might have data in wrong format • Who can detect the faults? § File. Reader constructor will throw an exception when file does not exist § Methods that process input need to throw exception if they find error in data format Continued…

A Complete Program (Cont’d) • What exceptions can be thrown? § File. Not. Found.

A Complete Program (Cont’d) • What exceptions can be thrown? § File. Not. Found. Exception can be thrown by File. Reader constructor § IOException can be thrown by close method of File. Reader § Bad. Data. Exception, a custom checked exception class Continued…

A Complete Program (Cont’d) • Who can remedy the faults that the exceptions report?

A Complete Program (Cont’d) • Who can remedy the faults that the exceptions report? § Only the main method of Data. Set. Tester program interacts with user • Catches exceptions • Prints appropriate error messages • Gives user another chance to enter a correct file

File Data. Set. Tester. java 01: import java. io. File. Not. Found. Exception; 02:

File Data. Set. Tester. java 01: import java. io. File. Not. Found. Exception; 02: import java. io. IOException; 03: import java. util. Scanner; 04: 05: public class Data. Set. Tester 06: { 07: public static void main(String[] args) 08: { 09: Scanner in = new Scanner(System. in); 10: Data. Set. Reader reader = new Data. Set. Reader(); 11: 12: boolean done = false; 13: while (!done) 14: { 15: try Continued… 16: {

File Data. Set. Tester. java 17: 18: 19: 20: 21: 22: 23: 24: 25:

File Data. Set. Tester. java 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: System. out. println("Please enter the file name: "); String filename = in. next(); double[] data = reader. read. File(filename); double sum = 0; for (double d : data) sum = sum + d; System. out. println("The sum is " + sum); done = true; } catch (File. Not. Found. Exception exception) { System. out. println("File not found. "); } catch (Bad. Data. Exception exception) { Continued… System. out. println ("Bad data: " + exception. get. Message());

File Data. Set. Tester. java 33: 34: 35: 36: 37: 38: 39: 40: }

File Data. Set. Tester. java 33: 34: 35: 36: 37: 38: 39: 40: } } catch (IOException exception) { exception. print. Stack. Trace(); } } }

The read. File method of the Data. Set. Reader class • Constructs Scanner object

The read. File method of the Data. Set. Reader class • Constructs Scanner object • Calls read. Data method • Completely unconcerned with any exceptions Continued…

The read. File method of the Data. Set. Reader class • If there is

The read. File method of the Data. Set. Reader class • If there is a problem with input file, it simply passes the exception to caller public double[] read. File(String filename) throws IOException, Bad. Data. Exception // File. Not. Found. Exception is an IOException { File. Reader reader = new File. Reader(filename); try { Scanner in = new Scanner(reader); read. Data(in); } Continued…

The read. File method of the Data. Set. Reader class finally { reader. close();

The read. File method of the Data. Set. Reader class finally { reader. close(); } return data; }

The read. File method of the Data. Set. Reader class • Reads the number

The read. File method of the Data. Set. Reader class • Reads the number of values • Constructs an array • Calls read. Value for each data value private void read. Data(Scanner in) throws Bad. Data. Exception { if (!in. has. Next. Int()) throw new Bad. Data. Exception("Length expected"); int number. Of. Values = in. next. Int(); data = new double[number. Of. Values]; for (int i = 0; i < number. Of. Values; i++) read. Value(in, i); if (in. has. Next()) throw new Bad. Data. Exception("End of file expected"); }

The read. File method of the Data. Set. Reader class • Checks for two

The read. File method of the Data. Set. Reader class • Checks for two potential errors 1. File might not start with an integer 2. File might have additional data after reading all values • Makes no attempt to catch any exceptions

The read. File method of the Data. Set. Reader class private void read. Value(Scanner

The read. File method of the Data. Set. Reader class private void read. Value(Scanner in, int i) throws Bad. Data. Exception { if (!in. has. Next. Double()) throw new Bad. Data. Exception("Data value expected"); data[i] = in. next. Double(); }

Scenario 1. Data. Set. Tester. main calls Data. Set. Reader. read. File 2. read.

Scenario 1. Data. Set. Tester. main calls Data. Set. Reader. read. File 2. read. File calls read. Data 3. read. Data calls read. Value 4. read. Value doesn't find expected value and throws Bad. Data. Exception 5. read. Value has no handler for exception and terminates Continued…

Scenario 6. read. Data has no handler for exception and terminates 7. read. File

Scenario 6. read. Data has no handler for exception and terminates 7. read. File has no handler for exception and terminates after executing finally clause 8. Data. Set. Tester. main has handler for Bad. Data. Exception; handler prints a message, and user is given another chance to enter file name

File Data. Set. Reader. java 01: import java. io. File. Reader; 02: import java.

File Data. Set. Reader. java 01: import java. io. File. Reader; 02: import java. io. IOException; 03: import java. util. Scanner; 04: 05: /** 06: Reads a data set from a file. The file must have // the format 07: number. Of. Values 08: value 1 09: value 2 10: . . . 11: */ 12: public class Data. Set. Reader Continued… 13: {

File Data. Set. Reader. java 14: 15: 16: 17: 18: 19: 20: 21: 22:

File Data. Set. Reader. java 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: /** Reads a data set. @param filename the name of the file holding the data @return the data in the file */ public double[] read. File(String filename) throws IOException, Bad. Data. Exception { File. Reader reader = new File. Reader(filename); try { Scanner in = new Scanner(reader); read. Data(in); } finally { reader. close(); } Continued…

File Data. Set. Reader. java 32: 33: 34: 35: 36: 37: 38: 39: 40:

File Data. Set. Reader. java 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: return data; } /** Reads all data. @param in the scanner that scans the data */ private void read. Data(Scanner in) throws Bad. Data. Exception { if (!in. has. Next. Int()) throw new Bad. Data. Exception("Length expected"); int number. Of. Values = in. next. Int(); data = new double[number. Of. Values]; for (int i = 0; i < number. Of. Values; i++) read. Value(in, i); Continued…

File Data. Set. Reader. java 48: 49: 50: 51: 52: 53: 54: 55: 56:

File Data. Set. Reader. java 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: if (in. has. Next()) throw new Bad. Data. Exception("End of file expected"); } /** Reads one data value. @param in the scanner that scans the data @param i the position of the value to read */ private void read. Value(Scanner in, int i) throws Bad. Data. Exception { Continued…

File Data. Set. Reader. java 60: 61: 62: 63: 64: 65: 66: } if

File Data. Set. Reader. java 60: 61: 62: 63: 64: 65: 66: } if (!in. has. Next. Double()) throw new Bad. Data. Exception("Data value expected"); data[i] = in. next. Double(); } private double[] data;