1 / 17

Catching Exceptions

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).

carmenh
Télécharger la présentation

Catching Exceptions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  2. 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 catchclause 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 InputStreamReader(System.in);   try { int [] list = new int[max]; } catch ( NegativeArraySizeException exception) { System.out.println(“how many values??”); max = Integer.parseInt(console.readLine()); int [] list = new int[max]; } try{ System.out.println(“Enter” + max+”values one/line"); for (int index = 0; index < max; index ++) list[index] = Integer.parseInt(console.readLine()); } catch (NumberFormatException exception) { throw new IllegalStateException(“average can’t be computed”); } catch (IndexOutofBounds 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 { 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 tryblock • Can also be combined with catchclauses

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

  11. A Complete Example • Program  • reads coin descriptions from file •  adds coins to purse • prints total • What can go wrong? • File might not exist • File might have data in wrong format • Who can detect the faults? • main method of PurseTestinteracts with user • main method can report errors • Other methods pass exceptions to caller

  12. The readmethod of the Coin class Distinguishes between expected and unexpected end of file 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 • 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; } }

  14. The readFile method of the Purseclass • finallyclause closes files if exception happens • public void readFile(String filename) throws IOException • { • BufferedReader in = null; try { 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) { Filename = JOptionPane.showInputDialog("Try another file:"); if (filename == null) done =true; } }

  17. Scenario • PurseTest.main calls Purse.readFile • Purse.readFile calls Purse.read • Purse.readcalls Coin.read • Coin.read throws an EOFException • Coin.readhas no handler for the exception and terminates immediately.  • Purse.read has no handler for the exception and terminates immediately • Purse.readFile has no handler for the exception and terminates immediately after executing the finally clause and closing the file.  • PurseTest.main has a handler for anIOException, 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.

More Related