In Java, when an error occurs, it "throws" an Exception. We use a Try-Catch block to "catch" that exception and handle it gracefully without stopping the whole program.
The Keyword Quartet
try: Wrap the "dangerous" code that might fail here.catch: If an error happens in thetryblock, the code jumps here. This is where you put your "Plan B."finally: This block runs no matter what, even if there was no error. It's perfect for "cleaning up" (like closing a file).throw: Used to manually create an error (e.g., "If age < 18, throw an error").
The Code Example:
public class ExceptionDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
try {
System.out.println("Attempting to access the 10th element...");
// This will fail because the array only has 3 items
System.out.println(numbers[10]);
System.out.println("This line will never run!");
} catch (ArrayIndexOutOfBoundsException e) {
// Plan B: Handle the specific error
System.out.println("ERROR: You tried to access an index that doesn't exist!");
System.out.println("Message: " + e.getMessage());
} catch (Exception e) {
// General safety net for any other types of errors
System.out.println("Something else went wrong.");
} finally {
// This always runs
System.out.println("Cleanup: Execution of the try-catch block is finished.");
}
System.out.println("\nLook! The program is still running and didn't crash.");
}
}Expected output:
Attempting to access the 10th element...
ERROR: You tried to access an index that doesn't exist!
Message: Index 10 out of bounds for length 3
Cleanup: Execution of the try-catch block is finished.
Look! The program is still running and didn't crash.Attempting to access the 10th element...
ERROR: You tried to access an index that doesn't exist!
Message: Index 10 out of bounds for length 3
Cleanup: Execution of the try-catch block is finished.
Look! The program is still running and didn't crash.