Java program to demonstrate the use of finally block
GD.java
class GD
{
    public static void main(String args[])
    {
        String s=null;
        try
        {
            System.out.println("Length: "+s.length());
        }
        catch(Exception e)
        {
            System.out.println("Exception caught");
        }
        finally
        {
            System.out.println("Finally block always get executed");
        }
    }
}
Output
godarda@gd:~$ javac GD.java
godarda@gd:~$ java GD Exception caught Finally block always get executed godarda@gd:~$
Java program to demonstrate the use of finally block
GD.java
class GD
{
    public static void main(String args[])
    {
        String s=null;
        try
        {
            System.out.println("Length: "+s.length());
        }
        catch(ArithmeticException e)
        {
            System.out.println("Exception caught in the first catch block");
        }
        catch(RuntimeException e)
        {
            System.out.println("Exception caught in the second catch block");
        }
        catch(Exception e)
        {
            System.out.println("Exception caught in the third catch block");
        }
        finally
        {
            System.out.println("Finally block always get executed");
        }
    }
}
Output
godarda@gd:~$ javac GD.java
godarda@gd:~$ java GD Exception caught in the second catch block Finally block always get executed godarda@gd:~$
The following try and finally block sequence is allowed
GD.java
class GD
{
    public static void main(String args[])
    {
        String s=null;
        try
        {
            System.out.println("Length: "+s.length());
        }
        finally
        {
            System.out.println("Finally block always get executed");
        }
    }
}
Output
godarda@gd:~$ javac GD.java
godarda@gd:~$ java GD Finally block always get executed Exception in thread "main" java.lang.NullPointerException at GD.main(GD.java:8) godarda@gd:~$
Comments and Reactions