16 - 02/28/09 19:50:15 CS 61B: Lecture 16 Friday, February...

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

View Full Document Right Arrow Icon
02/28/09 19:50:15 1 16 CS 61B: Lecture 16 Friday, February 27, 2009 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 proceed as usual, 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 the method ends 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.

Page1 / 2

16 - 02/28/09 19:50:15 CS 61B: Lecture 16 Friday, February...

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