• Try-catch and finally statement in Java

    try-catch Statement

    In Java default exception handler defined by Java runtime system is useful for debugging. There may be cases where we will want to handle an exception by ourselves. Doing so provides two benefits.

    •  It allows us to find the error.
    •  It prevents the program from automatically terminating.

    To guard against and handle a runtime error, we simply enclose the code that we want to monitor inside a try block. Immediately following the try block we include a catch clause that specifies exception type that we wish to catch. A try and its catch statement form a unit. The scope of the catch clause is restricted to those statements by the immediately preceding try statement. A catch statement can’t catch an exception thrown by another statement. The goal of well constructed catch clause should be to resolve exceptional condition and then continue on as if the error had never happened.

    Finally clause:

    When exceptions are thrown executions in a method rather abrupt, non-linear path that alters the normal flow through the method depending upon how the method is coded. It is even possible for an exception to cause the method to return pre-maturity. This is problematic in many cases like if a method opens a file upon entry and closes it upon exit. Then we will want the code that closes the file to be by-passed by the exception handling mechanism. The finally keyword is designed to solve this problem.

    Finally creates a block of code that will be executed after a try catch block has completed and before the code following the try catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown the finally block will execute even if no catch statement matches the exception. This can be useful in closing file handles and freeing up another resources that might have been allocated at the beginning of a method with the intent of disposing them before returning.


    class DivCal
    {
    public static void main(String []s)
    {
    int a=0,b=5;
    try
    {
    int c=b/a;
    }
    catch(ArithmeticException e)
    {
    System.out.println(“Divide by Zero is not allowed”);
    }
    finally
    {
    System.out.println(“Inside finally block”);
    }
    }
    }


  • You might also like

    No comments:

    Post a Comment

search topics

NEWSLETTER

Get All The Latest Updates Delivered Straight Into Your Inbox For Free!