Exception handling
Mon Jul 08 2024 16:06:13 GMT+0000 (Coordinated Universal Time)
Saved by
@projectrock
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Attempt to divide by zero
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// This block will execute when an ArithmeticException is caught
System.out.println("Error: Division by zero is not allowed.");
} finally {
// This block will always execute
System.out.println("This is the finally block, it always executes.");
}
try {
// Attempt to access an invalid array index
int[] array = {1, 2, 3};
System.out.println("Array element: " + array[5]);
} catch (ArrayIndexOutOfBoundsException e) {
// This block will execute when an ArrayIndexOutOfBoundsException is caught
System.out.println("Error: Array index out of bounds.");
} finally {
// This block will always execute
System.out.println("This is the finally block for array access, it always executes.");
}
try {
// Manually throwing an exception
throwException();
} catch (Exception e) {
// This block will execute when a general Exception is caught
System.out.println("Caught an exception: " + e.getMessage());
} finally {
// This block will always execute
System.out.println("This is the finally block for throwException, it always executes.");
}
}
// Method to demonstrate exception handling
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
// Method to demonstrate manually throwing an exception
public static void throwException() throws Exception {
throw new Exception("This is a manually thrown exception.");
}
}
content_copyCOPY
Comments