Is it possible to write multiple catch blocks?

Hello Everyone, I have completed my java certification and I am preparing myself for my upcoming interviews. I am confused in Is it possible to write multiple catch blocks under a single try block? This question was put in my last interview and my answer was no, it is not possible then the interviewer gave me a code which i mentioned below. Can anyone can this and explain me the code? or anyone who is an expert in java so please suggest me more trending java interview questions list.

public class Example {
public static void main(String args[]) {
try {
int a[]= new int[10];
a[10]= 10/0;
}
catch(ArithmeticException e)
{
System.out.println(“Arithmetic exception in first catch block”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index out of bounds in second catch block”);
}
catch(Exception e)
{
System.out.println(“Any exception in third catch block”);
}
}

Hi,

of course it is possible to have multiple catch blocks after a single try block.

But they need to be ordered from concrete exceptions to generic exceptions as the try/catch construct ends after the first catch block which has matched the thrown exception.

The division by zero will throw an ArithmeticException, adressing a[10] will throw an ArrayIndexOutOfBoundsException.
a[10] points to the eleventh element of the array which does not exist as the array has only 10 elements, indexed from 0 to 9.

The catch block will indicate in which order the calucation and assignment are performed.

Regards,
Holger

Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception. You can have try block without a catch block.

For this way you can do that:

There can be multiple catch blocks (as said in other answers already), but only the one that first matches the exception type is executed. That means you need to order the catch blocks properly. For example:

try
{
}
catch (Exception exp1)
{
    // Block 1
}
catch (IOException exp2)
{
    // Block 2
}

Block 2 will never be executed, as block 1 catches every exception (all exception classes are derived from Exception).

try
{
}
catch (IOException exp1)
{
    // Block 1
}

catch (Exception exp2)
{
    // Block 2
}

In this example, block 2 will only be executed if the exception is not an IOException or derived from IOException. If an IOException is thrown, only block 1 will execute, block 2 will not.

To know more interview question visit here.

1 Like