What is multi-catch block in java?
What if in a code you by mistake access an element of an array which is not present in array. For example if the array contains 5 elements and you are accessing the sixed element. It will give you an error, because you are trying to access element which is not present in the array.
If you are using try-catch but you haven't specified the exception then you will get an error. To solve the error or to print error message instead of exception.
You need to add catch method specifying the exception. In this way you can add multiple catch blocks. You can also add multiple exception in one catch statements. Since you can use this if number of exception wants to print same message.
This concept of having multiple exceptions in one catch was introduced in 1.7 version. If you are working on 1.6 then it will not work.
A try block can be followed by one or more catch block.Each catch block must contain a different exception handler.so if you have to perform different tasks at the occurrence of different exceptions,use java multi catch block.
1.At a time only one exception occurs and at a time only one catch block is executed.
2.All the catch blocks must be ordered from most specific to most general i,e. catch for ArithmeticException must come before catch for exception.
public class MultipleBlock
public static void main(String args)
int a=new int;
System.out.println("Arithmetic Exception Occurs");
System.out.println("ArrayOutOfBounds Exception Occurs");
System.out.println("parent exception occurs");
System.out.println("rest of the code");
Output: Arithmetic Exception occurs
rest of the code