Nested 'try' statements in Java

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

  1. Sanskruti

    Sanskruti New Member

    Joined:
    Jan 7, 2007
    Messages:
    108
    Likes Received:
    18
    Trophy Points:
    0
    Occupation:
    Software Consultant
    Location:
    Mumbai, India
    Just like the [thread=4167]multiple catch blocks[/thread], we can also have multiple try blocks. These try blocks may be written independently or we can nest the try blocks within each other, i.e., keep one try-catch block within another try-block. The program structure for nested try statement is:
    Code:
    try
    {
    	// statements
    	// statements
    	
    	try
    	{
    		// statements
    		// statements
    	} 
    	catch (<exception_two> obj)
    	{
    		// statements
    	} 
    
    	// statements
    	// statements
    } 
    catch (<exception_two> obj)
    {
    	// statements
    }
    
    Consider the following example in which you are accepting two numbers from the command line. After that, the command line arguments, which are in the string format, are converted to integers. If the numbers were not received properly in a number format, then during the conversion a NumberFormatException is raised otherwise the control goes to the next try block. Inside this second try-catch block the first number is divided by the second number, and during the calculation if there is any arithmetic error, it is caught by the inner catch block.

    Code:
    class Nested_Try
    {
    	public static void main (String args [ ] )
    	{
    		try
    		{
    			int a = Integer.parseInt (args [0]);
    			int b = Integer.parseInt (args [1]);
    			int quot = 0;
    
    			try
    			{
    				quot = a / b;
    				System.out.println(quot);
    			} 
    			catch (ArithmeticException e)
    			{
    				System.out.println("divide by zero");
    			}
    		} 
    		catch (NumberFormatException e)
    		{
    			System.out.println ("Incorrect argument type");
    		}
    	}
    }
    
    The output of the program is:

    If the arguments are entered properly like:

    Code:
    [COLOR=RoyalBlue] java Nested_Try 24 6
     4
    [/COLOR]
    If the argument contains a string than the number:

    Code:
    [COLOR=RoyalBlue] java Nested_Try 24 aa
     Incorrect argument type
    [/COLOR]
    If the second argument is entered zero:
    Code:
    [COLOR=RoyalBlue] java Nested_Try 24 0
     divide by zero
    [/COLOR]
     

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