try, catch, and finally keywords

try catch syntax

             v---------------------------------'
>>-try-Block-+-catch-(-Type-Identifier-)-Block-+-><

try finally syntax

             v---------------------------------'
>>-try-Block-+---------------------------------+-finally-Block-><
             '-catch-(-Type-Identifier-)-Block-'

Description
When a Java program violates the semantic constraints of the Java language, a Java Virtual Machine signals this error to the program as an exception. An example of such a violation is an attempt to index outside the bounds of an array. When an exception occurs (it is said to be thrown), control is transferred from the code that caused the exception to the nearest enclosing catch clause of a try statement that handles the exception.

A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control is transferred to the first such catch clause. If the try statement has a finally clause, then another block of code is executed, no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

A try statement may have catch clauses (also called exception handlers). A catch clause must have exactly one parameter (which is called an exception parameter); the declared type of the exception parameter must be the class Throwable or a subclass of Throwable, or a compilation error occurs. The scope of the parameter variable is the block of the catch clause. An exception parameter must not have the same name as a local variable or parameter in whose scope it is declared, or a compilation error occurs.

The try statement is declared as follows:

try {
    // statement
} catch (ExceptionClass e) {
    // statement
}

The finally keyword ensures that an action will be performed, regardless of whether or not an exception is thrown.  If an exception is thrown, two things can happen:

  1. The exception is caught and the statements in the catch block are executed.   Whether an exception is thrown in this catch block or not, the finally block is always executed.
  2. The exception is not caught because there is no corresponding catch block.  The finally block is then executed and the exception continues to be thrown to the next try/catch/finally statement.

If a finally block throws an exception, the old exception is discarded, and the new exception is thrown to the next enclosing try/catch/finally statement.

The try finally statement is declared as follows:

try {
    // statement
} catch (ExceptionClass e) {
    // this catch is optional
} finally {
   // statement that will always be executed
}

Example
In the following example, the exception BlewIt is thrown by the method blowUp:

class BlewIt extends Exception {
    BlewIt() { }
    BlewIt(String s) { super(s); }
}

class Test {
    static void blowUp() throws BlewIt {
        throw new BlewIt();
    }

    public static void main(String[] args) {
        try {
            blowUp();
        } catch (RuntimeException r){
             System.out.println("RuntimeException:" + r);
        } catch (BlewIt b) {
            System.out.println("BlewIt");
        }
    }
}

The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt, which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is as follows:

BlewIt

Using the exception class BlewIt from the previous example, the following example demonstrates the use of the finally statement:

class Test {
    static void blowUp() throws BlewIt {
        throw new NullPointerException();
    }

    public static void main(String[] args) {
        try {
            blowUp();
        } catch (BlewIt b) {
             System.out.println("BlewIt");
        } finally {
             System.out.println("Uncaught Exception");
        }
    }
}


The above example produces the following output.

Uncaught Exception
java.lang.NullPointerException
        at Test.blowUp(Test.java:7)
        at Test.main(Test.java:11)

The NullPointerException (which is a kind of RuntimeException) that is thrown by method blowUp is not caught by the try statement in main, because a NullPointerException is not assignable to a variable of type BlewIt. This causes the finally clause to execute, after which the thread executing main, which is the only thread of the test program, terminates because of an uncaught exception, which results in printing the exception name and a simple backtrace.

ngrelr.gif (548 bytes)
Syntax diagrams
Java types
throw keyword
throws keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.