try-catch-finally StructurePurpose:
- To "try" code that may generate and exception and "catch" that exception.
Mechanics:
try {/* Statements which may throw an exception */
}- catch(<Throwable 1> <exception handler
1>) {
- /* Statements to do if an exeption of type Throwable 1 is thrown */
}- catch(<Throwable 2> <exception handler
2>) {
- /* Statements to do if an exeption of type Throwable 2 is thrown */
}- catch(<Throwable n> <exception handler
n>) {
- /* Statements to do if an exeption of type Throwable n is thrown */
}- finally {
- /* Statements to do regardless of whether or not an exception is thrown. */
}
Example:
try {/* Some code that may throw a ClassCastException or a NullPointerException */
}- catch (ClassCastException c) {
- /* Statements to do if a ClassCastException is thrown */
}- catch (NullPointerException n) {
- /* Statements to do if a NullPointerException is thrown */
}- finally {
- /* Statements to do regardless of whether or not an exception is thrown. */
}
Usage:
- <Throwable> must be of the class
Throwableor one of its subclasses. - <exception handler> is any valid identifier name and is the variable where the exception is stored.
Restrictions:
- The programmer encloses in a
tryblock the code that may generate an exception. Thetryblock is immediately followed by one or morecatchblocks. Eachcatchblock specifies the type of exception it can catch and contains and exception handler. After the lastcatchblock, an optionalfinallyblock provides code that always executes regardless of whether or not an exception occurs.
email suggestions to: cs015tas@cs.brown.edu
