| Java introduces a new concept in exception
handling: the finally clause.
The finally clause sets apart a block of code that is always executed. |
| |
| Example of a finally clause: |
| |
import java.io.* ;
import java.lang.Exception ;
public class MultiThrowFin
{
public static void main( String[] args )
{
try
{
alpha() ;
}
catch( Exception e )}
{
System.out.println( "Caught exception " ) ;
}
finally()
{
System.out.println( "Finally. " ) ;
}
}
} |
| |
| In normal execution (that is, when no exceptions are thrown), the
finally block is executed immediately after the try block. |
| When an exception is thrown, the finally block is executed before
control passes to the caller. |
| If alpha() throws an exception, it is caught in the
catch block and then the finally block is executed. |
| If alpha() does not throw an exception, the finally block
is executed after the try block. If any code in a try block
is executed, the finally block is executed as well. |