Multiple Catch Blocks

0
395

Multiple Catch Blocks:

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

Syntax

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.

Example

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

try {
file
= new FileInputStream(fileName);
x
= (byte) file.read();
}catch(IOException i) {
i
.printStackTrace();
return 1;
}catch(FileNotFoundException f) // Not valid! {
f
.printStackTrace();
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) {
logger.log(ex);
throw ex;

SHARE
Previous articleAndroid Tutorial
Next articleWhat is CSS?