Experiment 06: Import Public Class Public Static Void New Try
Experiment 06: Import Public Class Public Static Void New Try
/*
6.Exception handling: Implement a program to handle Arithmetic exception,
Array Index Out of Bounds. The user enters two numbers Num1 and Num2. The
division of Num1 and Num2 is displayed. If Num1 and Num2 are not integers,
the program would throw a Number Format Exception. If Num2 were zero, the
program would throw an Arithmetic Exception. Display the exception
*/
import java.util.Scanner;
// Perform division
int result = num1 / num2;
System.out.println("Result of division (Num1 / Num2): " +
result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: Division by zero is
not allowed.");
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: Please enter valid
integers.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception: Tried
to access an invalid array index.");
} finally {
scanner.close();
System.out.println("Program execution completed.");
}
}
}
Output:
//Test 1
Enter the first number (Num1): 10
Enter the second number (Num2): 0
Arithmetic Exception: Division by zero is not allowed. Program
execution completed.
//Test 2
Enter the first number (Num1): ten
Enter the second number (Num2): five
Number Format Exception: Please enter valid integers. Program
execution completed.
//Test 3
Enter the first number (Num1): 10
Enter the second number (Num2): 2
Result of division (Num1 / Num2): 5
Array Index Out of Bounds Exception: Tried to access an invalid array
index. Program execution completed.