Java Exception Handling (try-catch-finally)
An exception is an abnormal event that occurs during execution and disrupts the normal flow of instructions. Java's robust `try-catch-finally` mechanism allows you to detect errors, handle them gracefully, and ensure cleanup code always runs.
"Exception handling is like a trapeze safety net: you TRY the difficult acrobatic flip. If you slip (catch an exception), the safety net catches you safely so the show can continue, and FINALLY the stage lights are turned off at the end of the night."
Deep Dive: How It Works
`try`: Encloses code that might potentially throw an exception.
`catch (ExceptionType e)`: Catches and handles the specific error if it occurs inside the try block.
`finally`: Code that is GUARANTEED to execute, whether an exception occurred or not (used for closing files/connections).
Common exceptions: `ArithmeticException` (e.g. division by zero), `NullPointerException`, `ArrayIndexOutOfBoundsException`, `NumberFormatException`.
Syntax Blueprint
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Cleanup always runs.");
}Catch specific exception types. Finally block always executes.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Catching generic Exception before specific onesWhy it happens: Catching Exception first swallows everything, preventing specific handlers from running.
How to fix: Order catch blocks from most specific exception to most general.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Handle array index exception
Wrap the array access arr[5] in a try-catch block.
Catch ArrayIndexOutOfBoundsException e and print "Index out of range!".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.