Syllabus / Java / Phase 4: Collections & Error Handling (Days 17–21)
Intermediate

Exception Handling Fundamentals

📂 Phase 4: Collections & Error Handling (Days 17–21) · Java

An exception is an event that disrupts the normal flow of a program at runtime. Exception handling lets your code respond gracefully instead of crashing outright.

Basic try-catch-finally Structure

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
    System.out.println("This block always runs, error or not");
}

Checked vs Unchecked Exceptions

CheckedUnchecked
Must be declared (throws) or caught — enforced at compile timeOccur at runtime, not enforced by the compiler
IOException, SQLExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException

Multiple Catch Blocks

try {
    String s = null;
    System.out.println(s.length());
} catch (NullPointerException e) {
    System.out.println("Null reference error");
} catch (Exception e) {
    System.out.println("Some other error occurred");
}
Always order catch blocks from most specific to most general — Java will not compile if a general Exception catch comes before a more specific one, since the specific catch would become unreachable.

throw vs throws

KeywordPurpose
throwActually triggers an exception at a specific line
throwsDeclares that a method might throw a checked exception, in its signature
public void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException("Not enough balance");
    }
}

try-with-resources

Automatically closes resources (like file streams) once the try block finishes, even if an exception occurs — avoids manually writing a finally block just to call close().

try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
    System.out.println(reader.readLine());
} catch (IOException e) {
    System.out.println("File error: " + e.getMessage());
}