try

The try keyword executes control statements.

Purpose

The try keyword is used to execute control statements with the ability to predeclare named exception handlers. A catch statement specifies exceptions that will be caught if thrown within a try block. A finally statement specifies a control block that will be executed after a try block is finished processing, including its exceptions, if any.

Syntax

try {statements} 
catch (exceptionType1 identifier) {statements}
[catch (exceptionType2 identifier) {statements}
...]
finally {statements}

Description

try-catch-finally statements define a block of code for exception handling. The try, catch, and finally blocks all begin and end with curly braces.

The try block must be followed by at least one catch or a finally statement, or both. The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it.

The catch statements are designed to handle a specific type of exception. The code within a catch statement is executed if an exception is caught. The exceptionType parameters declared in the catch statement specify the type of exception that the statement can handle and also provide identifiers that the catch statement can use to refer to the exception object that it is handling. The identifier must be of type Throwable or one of its subclasses.

The finally statement is guaranteed to be executed if any portion of the try statement is executed, regardless of how the code in the try and catch statements completes.

Example

Example 1

In this example, the division rule includes a try statement in its action part. When the x variable is equal to zero, the division throws an ArithmeticException. The exception is caught by the catch clause which prints a message.

try { 
        int z = y/x;
    }
    catch (ArithmeticException e) {
       note("Arithmetic Exception  ") ;
    }
Example 2

This example describes two catch statements, with one handler for each of the two types of exceptions that can be thrown within the try block: ArrayIndexOutOfBoundsException and IOException. When an exception occurs, the first catch statement that has an exception type compatible with the thrown exception is executed.

try {
    ... 
} 
catch (ArrayIndexOutOfBoundsException e) {
   note("Caught ArrayIndexOutOfBoundsException");
} 
catch (IOException e) {
   note("Caught IOException");
}
Example 3

This example shows a finally statement.

try{
...
}
finally {
      note("in finally");
}