When the code in a try block is executed,
follow these rules:
1) if exception occurs skip the code and jump straight to the specific exception, On its completion jump to the finally block and then to the statements that follow the finally block
This will not work if a System.exit(0) is seen in the catch block thus finally and the statements followed do not execute.
An example
class err
{
static
String s=null;
static public void main(String[]p)
{
try
{
s.substring(5);
System.out.println(new err().s);
}
catch(NullPointerException e)
{
System.out.println("in");
}
catch(Exception r)
{
System.out.println("in ex");
r.printStackTrace();
}
finally
{
System.out.println("doing finally");
}
System.out.println("out");
}
}
gives the output
[b]
D:\>java err
in
doing finally
out
D:\>
[\b]
2) If there is no exception the each statement in the catch block is executed followed by everything in the finally block. Then the control is given to the lines below the finally block.
Moral finally is executed no matter whether an exception occurs or not except when a call to exit has been invoked