15 - 02/25/09 16:25:41 CS 61B: Lecture 15 Wednesday,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
02/25/09 16:25:41 1 15 CS 61B: Lecture 15 Wednesday, February 25, 2009 Today’s reading: EXCEPTIONS ========== When a run-time error occurs in Java, the JVM "throws an exception," and the result is an error message. Oddly, an exception is a Java object (named Exception), and you can prevent the error message from printing and the program from terminating by "catching" the Exception that Java threw. Purpose #1: Surviving Errors ----------------------------- By catching exceptions, you can recover from an unexpected error. For instance, if you try to open a file that doesn’t exist or that you aren’t allowed to read, Java will throw an exception. You can catch the exception, print an error message, and continue, instead of letting the program crash. try { f = new FileInputStream("˜cs61b/pj2.solution"); i = f.read(); } catch (FileNotFoundException e1) { System.out.println(e1); } catch (IOException e2) { f.close(); } What does this code do? (a) It executes the code inside the "try" braces. (b) If the "try" code executes normally, we skip over the "catch" clauses. (c) If the "try" code throws an exception, Java does not finish the "try" code. It jumps directly to the first "catch" clause that matches the exception, and executes that "catch" clause. By "matches", I mean that the actual exception object thrown is the same class as, or a subclass of, the exception type listed in the "catch" clause. When the "catch" clause finishes executing, Java jumps to the next line of code immediately after all the "catch" clauses. The code within a "catch" clause is called an _exception_handler_. If the FileInputStream constructor fails to open the file, it will throw a FileNotFoundException. The line "i = f.read()" is not executed; execution jumps directly to the whiny exception handler. FileNotFoundException is a subclass of IOException, so the exception matches
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/21/2010 for the course CS 61B taught by Professor Canny during the Spring '01 term at University of California, Berkeley.

Page1 / 2

15 - 02/25/09 16:25:41 CS 61B: Lecture 15 Wednesday,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online