try

The try keyword is used to indicate a block of code in which an exception might occur. For each try statement, there must be at least one corresponding catch clause. If the exception occurs, the catch clause parameter is evaluated to determine whether it is capable of handling the exceptional condition. If the exceptional condition cannot be handled by any of the catch clauses corresponding to the try statement, then control is transferred up the chain of method calls and all the previous exception types are evaluated until one capable of handling the condition is found.

Note that if the try statement has a corresponding finally clause, then the body of the finally clause will be executed no matter whether the try block completes normally or abruptly, and no matter whether a catch clause is first given control.

The following example shows a typical try/catch/finally construct:

try
{
    // code within this block may cause an exception.
    .
    .
    .
}
catch( Exception1 e1 )
{
    // code within this block is executed only 
    // when an exception of type Exception1 occurs,
    // otherwise it is skipped over.
    .
    .
    .
}
catch( Exception2 e2 )
{
    // code within this block is executed only 
    // when an exception of type Exception2 occurs,
    // otherwise it too is skipped over.
    .
    .
    .
}
finally 
{

    // code within this block is always executed, 
    // regardless whether an exception within the 
    // try block occurs or not. This block is 
    // typically used for cleaning up.
    .
    .
    .
}