Exception Handling in Java

An exception is an unwanted event during execution that disrupts the normal flow of a program. Exception handling lets the program respond to it gracefully instead of crashing.

Keywords

KeywordPurpose
tryBlock of code that might throw an exception
catchHandles the exception
finallyAlways executes (cleanup)
throwThrows an exception explicitly
throwsDeclares exceptions a method may throw
Java
try {
    int r = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("Finally block always runs");
}
System.out.println("Program continues...");
Error: / by zero Finally block always runs Program continues...

Checked vs Unchecked

CheckedUnchecked
Checked at compile timeOccur at runtime
IOException, SQLExceptionNullPointerException, ArithmeticException
Must be handled or declaredHandling optional

Custom Exception

Java
class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) { super(msg); }
}

static void vote(int age) throws InvalidAgeException {
    if (age < 18) throw new InvalidAgeException("Age must be 18 or above");
    System.out.println("You can vote");
}

try { vote(15); }
catch (InvalidAgeException e) { System.out.println("Caught: " + e.getMessage()); }
Caught: Age must be 18 or above
Track your progress through the Java course