Exp 6 Java
Exp 6 Java
Here’s a simple Java program that demonstrates exception handling using try, catch, and
finally blocks. This program attempts to divide two numbers and catches an
ArithmeticException if division by zero occurs.
Output:
Exception Caught: Cannot divide by zero.
Execution completed.
Explanation:
Output:
Exception Caught: Cannot divide by zero.
Execution completed.
Explanation:
try {
// NumberFormatException Example
String invalidNumber = "abc";
int num = Integer.parseInt(invalidNumber);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("Exception Caught: Number format exception.");
}
try {
// ArrayIndexOutOfBoundsException Example
int[] arr = new int[5];
System.out.println(arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception Caught: Array index out of bounds exception.");
}
}
}
Output:
Exception Caught: Null pointer exception.
Exception Caught: Number format exception.
Exception Caught: Array index out of bounds exception.
Explanation:
Output:
Exception Caught: Age must be 18 or above.
Explanation: