• Java Exception Handling

    Java Exception Handling

    In Java Exception Handling, When Runtime Error occurred in program can be terminated abnormally and cannot display output or proper error message.

    So, at runtime if program can be terminated without inform any error that can be understand by programmer, it is very crucial to find an error in program or taken output.

    If programmer can be expected that error in his code, it can be handled by the java exception handling method.

    Java will help the programmer to handle exception using following five keywords : try, catch, throw, throws, and finally.

    Syntax :

    try and catch :

    try

    {

    Exception expected

    code segment;

    }

    catch(exception object)

    {

    when exception occurred

    code segment;

    }

    try and multiple catch block :

    try

    {

    Exception expected

    code segment;

    }

    catch(exception object)

    {

    when exception occurred

    code segment;

    }

    catch(exception object)

    {

    when exception occurred

    code segment;

    }

    try with multiple catch and finally :

    try

    {

    Exception expected

    code segment;

    }

    catch(exception object)

    {

    when exception occurred

    code segment;

    }

    catch(exception object)

    {

    when exception occurred

    code segment;

    }

    finally

    {

    Code Segment that must be executed

    either exception is raised or not.

    }

    finally blocked must be written last in the try…catch block.

    Example :

    import java.lang.*;

    import java.io.*;

    class  TryExample1

    {

    public static void main(String[] args)

    {

    int a, b, c;

    try

    {

    a = Integer.parseInt(args[0]);

    b = Integer.parseInt(args[1]);

    c = a + b;

    System.out.println(“The Sum is : ” + c);

    }

    catch(ArrayIndexOutOfBoundsException e)

    {

    System.out.println(“You cannot use args[] in proper way…”);

    }

    catch(NumberFormatException e)

    {

    System.out.println(“You cannot Enter Numeric values for Variables….”);

    }

    finally

    {

    System.out.println(“This Block Expected Any Time….”);

    }

    }

    }

    Appreciate my work :Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg thisShare on YummlyShare on VKFlattr the authorBuffer this page

Leave a Reply

Your email address will not be published. Required fields are marked *