Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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 SHOULDN’T HAPPEN !!!! THE PROGRAM SHOULD HANDLE (CATCH) EXCEPTION before THE PROGRAM TERMINATES !!

2 General Try Block Syntax General Try Block Syntax try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }

3 Perhaps the block of code can generate a number of exceptions.. prepare to catch each type…. try { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... } catch (ExceptionClass exceptionObject) { statement statement... }...

4 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

5 Catching Exceptions try { BufferedReader in = new BufferedReader( new FileReader(“filename.txt”)); String inputLine = in.readLine(); int age = Integer.parseInt(inputLine); age++; } catch (IOException exception) { age = 0; System.out.println(“file not found/default used“+ +exception); } catch (NumberFormatException exception) { age = 0; }

6 public void computeAvg ( int max) { BufferedReader console = new BufferedReader(new BufferedReader console = new BufferedReader(new InputStreamReader(System.in); InputStreamReader(System.in); try { int [] list = new int[max]; try { int [] list = new int[max]; } catch ( NegativeArraySizeException exception) { catch ( NegativeArraySizeException exception) { System.out.println(“how many values??”); System.out.println(“how many values??”); max = Integer.parseInt(console.readLine()); max = Integer.parseInt(console.readLine()); int [] list = new int[max]; int [] list = new int[max]; } try{ try{ System.out.println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) System.out.println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) list[index] = Integer.parseInt(console.readLine()); } list[index] = Integer.parseInt(console.readLine()); } catch (NumberFormatException exception) { throw new IllegalStateException(“average can’t be computed”); catch (NumberFormatException exception) { throw new IllegalStateException(“average can’t be computed”); } catch (IndexOutofBounds e) { catch (IndexOutofBounds e) { throw new IllegalStateException(“array full:average can’t be computed” + e); throw new IllegalStateException(“array full:average can’t be computed” + e);}

7 The finally Clause  Sometimes there is code which needs to be executed EVEN IF an exception occurred  Example: BufferedReader in; in = new BufferedReader(new FileReader(filename)); purse.read(in); in.close();  Must execute in.close() even if exception happens

8 The finally Clause Syntax try { statement statement... } finally { try { statement statement... } finally { statement statement... } statement statement... }

9 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 block  Can also be combined with catch clauses

10 BufferedReader in = null; try { in = new BufferedReader( new FileReader(filename)); purse.read(in); } finally { if (in !=null) in.close(); } try { in = new BufferedReader( new FileReader(filename)); purse.read(in); } finally { if (in !=null) in.close(); }

11 A Complete Example  Program  Program oreads lines coin quantities and coin names from file o adds coins to purse oprints total  What can go wrong? oFile might not exist oFile might have data in wrong format  Who can detect the faults? omain method of PurseTest interacts with user omain method can report errors oOther methods pass exceptions to caller

12 The read method of the Coin class //reads a value and name from file, stores as instance data public boolean read(BufferedReader in) throws IOException { String input =in.readLine(); if (input == null) // normal end of file return false; value = Double.parseDouble(input); // may throw unchecked NumberFormatException name = in.readLine(); if (name == null) // unexpected end of file throw new EOFException("Coin name expected"); return true; }

13 The read method of the Purse class Unconcerned with exceptions Unconcerned with exceptions Just passes them to caller Just passes them to caller public void read(BufferedReader in) throws IOException { boolean done = false; while (!done) { Coin c = new Coin(); if (c.read(in)) add(c); else done =true; } add(c); else done =true; }}

14 The readFile method of the Purse class finally clause closes files if exception happens public void readFile(String filename) throwsIOException { BufferedReader in = null; try { //two possible sources of IOExceptions in = new BufferedReader( new FileReader(filename)); read(in); } finally { if (in != null) in.close(); } }

15 User interaction in main If an exception occurs, user can specify another file name boolean done = false; String filename = JOptionPane.showInputDialog("Enter file name"); while (!done) { try { Purse myPurse = new Purse(); myPurse.readFile(filename); System.out.println("total=" + myPurse.getTotal()); done =true; }

16 catch (IOException exception) { System.out.println("Input/output error " + exception); } catch (NumberFormatException exception) { exception.printStackTrace(); // error in file format } if (!done) //an exception occurred { Filename = JOptionPane.showInputDialog("Try another file:"); if (filename == null) done =true; } }

17 Scenario 1. PurseTest.main calls Purse.readFile 2. Purse.readFile calls Purse.read 3. Purse.read calls Coin.read 4. Coin.read throws an EOFException 5. Coin.read has no handler for the exception and terminates immediately. 5. Coin.read has no handler for the exception and terminates immediately. 6. Purse.read has no handler for the exception and terminates immediately 7. Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file. 7. Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file. 8. PurseTest.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.


Download ppt "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."

Similar presentations


Ads by Google