When there are chances of occurring multiple exceptions of different types by the same set of statements then such situation can be handled using the nested try statements.
Nested try Statements
• When
there are chances of occurring multiple exceptions of different types by the
same set of statements then such situation can be handled using the nested try
statements.
• Following
is an example of nested try-catch statements -
Java Program[NestedtryDemo.java]
class
NestedtryDemo
{
public
static void main(String[] args)
{
try
{
int a =
Integer.parseInt (args [0]);
int b =
Integer.parseInt (args [1]);
int ans
= 0;
try
{
ans =
a/b;
System.out.println("The
result is "+ans);
}
catch
(ArithmeticException e)
{
System.out.println("Divide
by zero");
}
}
catch
(NumberFormatException e)
{
System.out.println
("Incorrect type of data");
}
}
}
Output
D:\>javac
NestedtryDemo.java
D:\>java
NestedtryDemo 20 10
The
result is 2
D:\>java
NestedtryDemo 20 a
Incorrect
type of data
D:\>java
NestedtryDemo 20 0
Divide
by zero
Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Exception Handling Java Programs - Nested try Statements
Object Oriented Programming
CS3391 3rd Semester CSE Dept | 2021 Regulation | 3rd Semester CSE Dept 2021 Regulation