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