Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute multiple catch blocks that correspond to one try block?

Tags:

java

c#

Consider I have a try block that contains 3 statements, and all of them cause Exceptions. I want all the 3 exceptions to be handled by their relevant catch blocks.. is it possible ?

something like this-->

class multicatch
{
    public static void main(String[] args)
    {
        int[] c={1};
        String s="this is a false integer";
        try
        {
            int x=5/args.length;
            c[10]=12;
            int y=Integer.parseInt(s);
        }
        catch(ArithmeticException ae)
        {
            System.out.println("Cannot divide a number by zero.");
        }
        catch(ArrayIndexOutOfBoundsException abe)
        {
            System.out.println("This array index is not accessible.");
        }
        catch(NumberFormatException nfe)
        {
            System.out.println("Cannot parse a non-integer string.");
        }
    }
}

Is it possible to obtain the following output? -->>

Cannot divide a number by zero.
This array index is not accessible.
Cannot parse a non-integer string.
like image 401
Srinivas Cheruku Avatar asked Jun 04 '13 21:06

Srinivas Cheruku


2 Answers

Is it possible to obtain the following output?

No, because only one of the exceptions will be thrown. Execution leaves the try block as soon as the exception is thrown, and assuming there's a matching catch block, it continues there. It doesn't go back into the try block, so you can't end up with a second exception.

See the Java tutorial for a general lesson in exception handling, and section 11.3 of the JLS for more details.

like image 148
Jon Skeet Avatar answered Oct 28 '22 10:10

Jon Skeet


If you want to catch multiple exceptions, you have to split your code across multiple try/catch blocks.

A better approach is to validate your data and log errors without triggering Exceptions to do this.

like image 32
Peter Lawrey Avatar answered Oct 28 '22 11:10

Peter Lawrey