Java program on Manual Exceptions with 'throw' keyword

In Java, a programmer can throw exceptions manually using 'throw' keyword.

PROGRAM:

import java.util.Scanner;

public class ManualException {
    public static void main(String[] args) {
        int num1, num2, result;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter value of num1");
        num1 = sc.nextInt();
        System.out.println("Enter value of num2");
        num2 = sc.nextInt();
        try {
            if (num1 >= num2) {
                result = num1 - num2;
                System.out.println(result);
            } else {
                throw new Exception("Mistake in subtraction");
            }
        } catch (Exception e) {
            System.out.println("Exception caught\n" + e.getMessage());
        }
    }

}

OUTPUT:

Enter value of num1
50
Enter value of num2
70
Exception caught
Mistake in subtraction

Popular Posts