Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Java Exceptions: finally (http://www.go4expert.com/articles/java-exceptions-finally-t4152/)

Sanskruti 5May2007 18:59

Java Exceptions: finally
 
The finally clause is written with the try-catch statement. It is guarenteed to be executed after a catch block or before the method quits.

Code: Java

try
{
    // statements
}
catch (<exception> obj)
{
    // statements
}
finally
{
    //statements
}

Take a look at the following example which has a catch and a finally block. The catch block catches the ArithmeticException which occurs for arithmetic error like divide-by-zero. After executing the catch block the finally is also executed and you get the output for both the blocks.

Code: Java

class Finally_Block
{
    static void division ( )
    {
        try
        {
            int num = 34, den = 0;
            int quot = num / den;
        }
        catch(ArithmeticException e)
        {
            System.out.println ("Divide by zero");
        }
        finally
        {
            System.out.println ("In the finally block");
        }
    }

    public static void main(String args[])
    {
        division ( );
    }
}

The output of the above program is:

Code:

Divide by zero
In the finally block

While dealing with exception handling, many times the program exception takes an abrupt path which hampers the normal flow of execution. This sometimes may have some undesirable effects. For example, assume a method that opens a file writes data to it and you abruptly break out of the method without closing the file. Under such situations the finally clause comes to the rescue. The program structure is given below;

Code: Java

class write_To_Stream
{
    public void open_Stream ( )
    {
        // Open the stream
    }

    public void writing_To_Stream ( )
    {
        try
        {
            // statement for writing to a stream
        }
        catch(Exception e)
        {
            // prematurely close the stream
        }
        finally
        {
            // prematurely close the stream
        }
    }
    public void close_Stream ( )
    {
        // close the stream
    }
}

public class classIO
{
    public static void main (String args [ ] )
    {
        // Instantiate and call the methods of Write_To_Stream class
    }
}

<< Java Exceptions: throws clause


All times are GMT +5.5. The time now is 21:34.