Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Nested 'try' statements in Java (http://www.go4expert.com/articles/nested-try-statements-java-t4168/)

Sanskruti 6May2007 15:12

Nested 'try' statements in Java
 
Just like the multiple catch blocks, 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: Java

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: Java

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:

java Nested_Try 24 6
 4

If the argument contains a string than the number:

Code:

java Nested_Try 24 aa
 Incorrect argument type

If the second argument is entered zero:
Code:

java Nested_Try 24 0
 divide by zero



All times are GMT +5.5. The time now is 04:26.