Thursday 23 June 2016

Java Tutorial : Java Exception handling (finally block)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=QuDO6t9kwkc&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Java Exception handling (finally block) 
Java Tutorial : Java Exception handling (finally block) 
FinallyDemo1.java
/*
 *  finally block will be executed, 
 *  Even if exception not occur.
 */

public class FinallyDemo1
{
    public static void main(String args[])
    {
        try
        {
            int b = 30 / 5;
            System.out.println("b = " + b);
        }
        catch (ArithmeticException arithmeticException)
        {
            arithmeticException.printStackTrace();
        }
        finally
        {
            System.out.println("finally block is always executed.");
        }
    }
}
Output
b = 6
finally block is always executed.
FinallyDemo2.java
/*
 *  finally block will be executed, even exception 
 *  occurs and it is not handled,
 */

public class FinallyDemo2
{
    public static void main(String args[])
    {
        try
        {
            int b = 30 / 0;
            System.out.println("b = " + b);
        }
        catch (IndexOutOfBoundsException indexOutOfBoundsException)
        {
            indexOutOfBoundsException.printStackTrace();
        }
        finally
        {
            System.out.println("finally block is always executed.");
        }
    }
}
Output
finally block is always executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at FinallyDemo2.main(FinallyDemo2.java:12)
FinallyDemo3.java
/*
 *  finally block will be executed, 
 *  Even if exception occurs and handled.
 */

public class FinallyDemo3
{
    public static void main(String args[])
    {
        try
        {
            int b = 30 / 0;
            System.out.println("b = " + b);
        }
        catch (ArithmeticException arithmeticException)
        {
            System.out.println("Divide by zero is not possible.");
        }
        finally
        {
            System.out.println("finally block is always executed.");
        }
    }
}
Output
Divide by zero is not possible.
finally block is always executed.
Click the below link to download the code:
https://sites.google.com/site/javaee4321/java/ExceptionDemo_finally_block_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ExceptionDemo_finally_block_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/969ffd88eb34c4fd42d966118b27490392b78865/BasicJava/ExceptionDemo_finally_block_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment