15 - 10/01/10 20:20:56 CS 61B: Lecture 15 Friday, October...

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

View Full Document Right Arrow Icon
10/01/10 20:20:56 1 15 CS 61B: Lecture 15 Friday, October 1, 2010 Today’s reading: EXCEPTIONS (continued) ========== The "finally" keyword --------------------- A finally clause can also be added to a "try." try { statementX; return 1; } catch (SomeException e) { e.printStackTrace(); return 2; } finally { f.close(); return 3; } If the "try" statement begins to execute, the "finally" clause will be executed at the end, no matter what happens. This example (which is contrived) always returns 3; never 1 or 2. If statementX causes a SomeException, the exception is caught, the "catch" clause is executed, and then the "finally" clause is executed. If statementX causes some other class of exception, the "finally" clause is executed immediately, then the exception continues to propagate down the stack. "finally" clauses are used to do things that need to be done in both normal and exceptional circumstances. (Again, closing files is an example.) In the example above, we’ve invoked the method "printStackTrace" on the exception we caught. When an exception is created, it takes a snapshot of the stack, which can be printed later. It is possible for an exception to occur in a "catch" or "finally" clause. An exception thrown in a "catch" clause will terminate the "catch" clause, but the "finally" clause will still get executed before the exception goes on. An exception thrown in a "finally" clause replaces the old exception, and terminates the "finally" clause and the method immediately. However. ..you can put a "try" clause inside a "catch" or "finally" clause, thereby catching those exceptions as well. Exception constructors ---------------------- By convention, most Throwables (including Exceptions) have two constructors. One takes no parameters, and one takes an error message in the form of a String. class MyException extends Exception {
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 01/10/2012 for the course CS 61B taught by Professor Canny during the Fall '01 term at University of California, Berkeley.

Page1 / 2

15 - 10/01/10 20:20:56 CS 61B: Lecture 15 Friday, October...

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