Catching Exceptions An exception may be thrown by
Catching Exceptions An exception may be thrown by a method when an exceptional occurance happens (and the method does not have the expertise to remedy the situation). The concept: perhaps the caller of the method would know what to do, and can ‘handle’ the problem. If the calling method does NOT handle the situation, the exception is thrown to it’s caller … and so forth. Eventually the exception reachs the main method. If main doesn’t ‘handle’ the exceptional situation, the program terminates with a stack trace. IDEALLY, THIS SHOULD’T HAPPEN !!!! THE PROGRAM SHOULD HANDLE (CATCH) EXCEPTION before THE PROGRAM TERMINATES !!
General Try Block Syntax try { statement. . . } catch (Exception. Class exception. Object) { statement. . . }
Perhaps the block of code can generate a number of exceptions. . prepare to catch each type…. try { statement. . . } catch (Exception. Class exception. Object) { statement. . . }. . .
Execution behavior ……. . • Statements in try block are executed • If no exceptions occur, catch clauses are skipped • If exception of matching type occurs, execution jumps to catch clause and execution continues • If exception of another type occurs, it is thrown to the calling method
Catching Exceptions try { Buffered. Reader in = new Buffered. Reader( new File. Reader(“filename. txt”)); String input. Line = in. read. Line(); int age = Integer. parse. Int(input. Line); age++; } catch (IOException exception) { age = 0; System. out. println(“file not found/default used“+ +exception); } catch (Number. Format. Exception exception) { age = 0; }
public void compute. Avg ( int max) { Buffered. Reader console = new Buffered. Reader(new Input. Stream. Reader(System. in); try { int [] list = new int[max]; } catch ( Negative. Array. Size. Exception exception) { System. out. println(“how many values? ? ”); max = Integer. parse. Int(console. read. Line()); int [] list = new int[max]; } try{ System. out. println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) list[index] = Integer. parse. Int(console. read. Line()); } catch (Number. Format. Exception exception) { throw new Illegal. State. Exception(“average can’t be computed”); } catch (Index. Outof. Bounds e) { throw new Illegal. State. Exception(“array full: average can’t be computed” + e);
The finally Clause • Sometimes there is code which needs to be executed EVEN IF an exception occurred • Example: Buffered. Reader in; in = new Buffered. Reader(new File. Reader(filename)); purse. read(in); in. close(); • Must execute in. close() even if exception happens
The finally Clause Syntax try { statement. . . } finally { statement. . . }
The finally Clause • Executed when try block comes to normal end • Executed if a statement in try block throws an exception, before exception is thrown out of try bloc • Can also be combined with catch clauses
Buffered. Reader in = null; try { in = new Buffered. Reader( new File. Reader(filename)); purse. read(in); } finally { if (in !=null) in. close(); }
A Complete Example • Program o reads coin descriptions from file o adds coins to purse o prints total • What can go wrong? o File might not exist o File might have data in wrong format • Who can detect the faults? o main method of Purse. Test interacts with user o main method can report errors o Other methods pass exceptions to caller
The read method of the Coin class Distinguishes between expected and unexpected end of file public boolean read(Buffered. Reader in) throws IOException { String input =in. read. Line(); if (input == null) // normal end of file return false; value = Double. parse. Double(input); // may throw unchecked Number. Format. Exception name = in. read. Line(); if (name == null) // unexpected end of file throw new EOFException("Coin name expected"); return true; }
The read method of the Purse class • Unconcerned with exceptions • Just passes them to caller public void read(Buffered. Reader in) throws IOException { boolean done = false; while (!done) { Coin c = new Coin(); if (c. read(in)) add(c); else done =true; } }
The read. File method of the Purse class • finally clause closes files if exception happens public void read. File(String filename) throws IOException { Buffered. Reader in = null; try { in = new Buffered. Reader( new File. Reader(filename)); read(in); } finally { if (in != null) in. close(); } }
User interaction in main • If an exception occurs, user can specify another file name boolean done = false; String filename = JOption. Pane. show. Input. Dialog("Enter name"); while (!done) { try { Purse my. Purse = new Purse(); my. Purse. read. File(filename); System. out. println("total=" + my. Purse. get. Total()); done =true; } file
catch (IOException exception) { System. out. println("Input/output error " + exception); } catch (Number. Format. Exception exception) { exception. print. Stack. Trace(); // error in file format } if (!done) { Filename = JOption. Pane. show. Input. Dialog("Try another file: "); if (filename == null) done =true; } }
Scenario calls Purse. read. File calls Purse. read calls Coin. read throws an EOFException Coin. read has no handler for the exception and terminates immediately. Purse. read has no handler for the exception and terminates immediately Purse. read. File has no handler for the exception and terminates immediately after executing the finally clause and closing the file. Purse. Test. main has a handler for an IOException , a superclass of EOFException. That handler prints a message to the user. Afterwards, the user is given another chance to enter a file name. Note that the statement printing the purse total has been skipped. 1. Purse. Test. main 2. 3. 4. 5. 6. 7. 8.
- Slides: 17