Multiple Catch Blocks


Multiple Catch Blocks:

Try blocks can followed by more than two catch blocks. They syntax for the two catch blocks looks like the below;


try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block

The past explanations exhibit three catch pieces, however you can have any number of them after a solitary attempt. In the event that an exemption happens in the ensured code, the special case is tossed to the main catch obstruct in the rundown. On the off chance that the information sort of the special case tossed matches ExceptionType1, it gets got there. If not, the special case goes down to the second catch articulation. This proceeds until the point when the special case either is gotten or falls through all gets, in which case the present strategy stops execution and the exemption is tossed down to the past technique on the call stack.


This coding segment displays how to use multiple catch/try statements:

try {
= new FileInputStream(fileName);
= (byte);
}catch(IOException i) {
return 1;
}catch(FileNotFoundException f) // Not valid! {
return 1;

Catching Type of multiple Exceptions

As java 7, user can handle multiple exception by using single catch block, this is used to simplifies the code. Below you will know the process of doing it:

catch (IOException|FileNotFoundException ex) {
throw ex;