Java Program to demonstrate nested try block
Program
public class NestedTryDemo {
public static void main(String args[]) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
try {
int div = a / b;
System.out.println("Division: " + div);
} catch (ArithmeticException arEx) {
System.out.println("Divide by zero exception: " + arEx.getMessage());
}
} catch (NumberFormatException nfEx) {
System.out.println("Incorrect argument type: " + nfEx.getMessage());
}
}
}
This Java program demonstrates the use of nested try-catch blocks to handle exceptions that might arise during runtime.
-
Outer
try
block:- The program expects two command-line arguments, which are read as
args[0]
andargs[1]
. - These arguments are converted from
String
toint
usingInteger.parseInt()
. - If the input arguments are not valid integers, a NumberFormatException will be thrown and caught in the outer
catch
block.
- The program expects two command-line arguments, which are read as
-
Inner
try
block:- Once the integers
a
andb
are successfully parsed, the program attempts to dividea
byb
in the innertry
block. - If
b
is0
, a Divide by Zero Exception (ArithmeticException) will be thrown and caught by the innercatch
block.
- Once the integers
-
Catch Blocks:
- The outer
catch
block handles invalid input (non-numeric arguments). - The inner
catch
block handles division by zero errors.
- The outer
Output 1
$ java NestedTryDemo 15 3
Division: 5
Output 2
$ java NestedTryDemo 23 a
Incorrect argument type: For input string: "a"
Output 3
$ java NestedTryDemo 6 0
Divide by zero exception: / by zero