Course contentsShow
← Java
Lesson 787 of 2,87019. Exception Hierarchy and Custom ExceptionsFree lesson

Compile-Time Enforcement of Checked Exceptions

See how the compiler forces you to either catch or declare checked exceptions, preventing unhandled exception propagation.

Compile-Time Enforcement of Checked Exceptions

What you'll learn: How the Java compiler actively prevents your code from compiling if you fail to handle or declare checked exceptions.


The Compiler as a Safety Net

Unlike unchecked exceptions (which the compiler ignores), checked exceptions trigger compile-time enforcement. This means the compiler scans your code and refuses to compile it unless you've done one of two things for every checked exception that might be thrown:

  1. Caught it with a try-catch block
  2. Declared it in your method signature using throws

Think of checked exceptions like mandatory safety inspections—the compiler acts as an inspector who won't let your program "leave the factory" until you've proven you've handled or acknowledged every potential checked exception.

Why This Matters

This enforcement prevents a common bug: forgetting to handle exceptional conditions. If a method throws IOException, the compiler forces you to acknowledge it. You cannot ignore it and hope for the best.

// This will NOT compile:
public void readFile() {
    FileReader fr = new FileReader("data.txt"); // FileNotFoundException is checked!
}

// You must either catch:
public void readFile() {
    try {
        FileReader fr = new FileReader("data.txt");
    } catch (FileNotFoundException e) {
        System.out.println("File not found");
    }
}

// Or declare:
public void readFile() throws FileNotFoundException {
    FileReader fr = new FileReader("data.txt");
}

Without the try-catch or throws, you'll get a compiler error like: "Unhandled exception: java.io.FileNotFoundException"

The Contract

When you see throws in a method signature, that's the method saying: "I might throw this checked exception, and you must deal with it." The compiler enforces this contract throughout your entire call chain until someone catches the exception.

Key Takeaway: The Java compiler enforces checked exceptions at compile time, refusing to build your code until you either catch the exception with try-catch or declare it with throws—ensuring exceptional conditions are never accidentally ignored.