In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try.
Nested Try-Catch Blocks
In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try. If an inner try statement does not have a matching catch statement for a particular exception, the control is transferred to the next try statement?s catch handlers that are expected for a matching catch statement. This continues until one of the catch statements succeeds, or until all of the nested try statements are done in. If no one catch statements match, then the Java run-time system will handle the exception.
The syntax of nested try-catch blocks is given below:
try { catch (Exception1 e)
{ catch (Exception 2 e2)
{
|
Lets have an example that uses the nested try-catch
blocks
import java.io.*;
|
Output of the program:
C:\Roseindia\>javac
NestedTry.java
C:\Roseindia\>java NestedTry
|
In this given example we have implemented nested try-catch blocks concept
where an inner try block is kept with in an outer try block, that's catch
handler will handle the arithmetic exception. But before that an ArrayIndexOutOfBoundsException
will be raised, if a file name is not passed as an argument while running the
program.
Now lets see, what will be
the output if we pass the file name student as an argument.
C:\Roseindia\>javac
NestedTry.java
C:\Roseindia\>java NestedTry student.txt File not found! |
If the outer try block's statements run
successfully then the inner try will raise an ArithmeticException as:
C:\Roseindia\>javac
NestedTry.java
C:\Roseindia\>java NestedTry student.txt divided by Zero |