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.

  1. Outer try block:

    • The program expects two command-line arguments, which are read as args[0] and args[1].
    • These arguments are converted from String to int using Integer.parseInt().
    • If the input arguments are not valid integers, a NumberFormatException will be thrown and caught in the outer catch block.
  2. Inner try block:

    • Once the integers a and b are successfully parsed, the program attempts to divide a by b in the inner try block.
    • If b is 0, a Divide by Zero Exception (ArithmeticException) will be thrown and caught by the inner catch block.
  3. Catch Blocks:

    • The outer catch block handles invalid input (non-numeric arguments).
    • The inner catch block handles division by zero errors.

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