Java Exceptions: finally

Discussion in 'Java' started by Sanskruti, May 5, 2007.

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India
    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:
    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:
    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:
    [COLOR=RoyalBlue]Divide by zero
    In the finally block[/COLOR]
    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:
    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
    	}
    }
    [thread=4151] << Java Exceptions: throws clause [/thread]
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice