We can write try catch block inside another try block. By having nested try catch blocks, we can separately handle multiple exceptions in the code.
Syntax -
try
{
try
{
//Code
}
catch( )
{
//Code
}
//Code
}
catch( )
{
//Code
}
Lets implement this on Eclipse IDE -
1. Launch Eclipse IDE, create new Java Project 'Project 47' as shown below -
2. Create a new Java Class file 'NestedTryCatchDemo.java' with main( ) method as shown below -
3. Create a set of statements which can throw more than one exceptions as shown below -
4. Lets keep the above code in the try block and handle the exception using the catch block as shown below (i.e. Using a single try catch blocks to handle two exceptions) -
5. Save and Run the Java Class 'NestedTryCatchDemo.java' and observe that only one exception out of two is handled and the exception details are displayed in the output as shown below -
6. Now write another try catch block inside the existing try catch block to handle the first exception separately as shown below -
7. Save and Run the Java Class 'NestedTryCatchDemo.java' and observe that two exception out of two are handled and the exception details are displayed in the output as shown below -
Hence we can use nested try catch blocks to handle the multiple exceptions separately in the program code.
Please comment below to feedback or ask questions.
No comments:
Post a Comment