Java program to demonstrate the use of finally block
Codeaft.java
class Codeaft
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Exception caught Finally block always get executed codeaft@codeaft:~$
Java program to demonstrate the use of finally block
Codeaft.java
class Codeaft
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Exception caught in the second catch block Finally block always get executed codeaft@codeaft:~$
The following try and finally block sequence is allowed
Codeaft.java
class Codeaft
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Finally block always get executed Exception in thread "main" java.lang.NullPointerException at Codeaft.main(Codeaft.java:8) codeaft@codeaft:~$
Comments and Reactions