Checked vs Unchecked Exceptions

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Checked Exceptions: Checked by the compiler at compile-time. You must handle them (using try-catch) or declare them (using throws), otherwise the code will not compile. (e.g., IOException).
  • Unchecked Exceptions: Not checked at compile-time. They occur at runtime and are subclasses of RuntimeException. You are not required to handle them. (e.g., NullPointerException).

Concept

Java forces developers to anticipate things that can go wrong outside of their control.

Checked Exceptions (The Exception class)

These represent conditions outside the immediate control of the program that a reasonable application should try to recover from. For example, if you try to read a file, the file might not exist. Java forces you to write a fallback plan.

Unchecked Exceptions (The RuntimeException class)

These represent programming bugs, logic errors, or improper use of an API. For example, dividing by zero, or accessing a null object reference. The compiler does not force you to handle these because you should ideally fix the bug rather than write a try-catch block for it.

Examples

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ExceptionsExample {
    public static void main(String[] args) {
        
        // --- UNCHECKED EXCEPTION (Compiles fine) ---
        String text = null;
        // If uncommented, throws NullPointerException at runtime.
        // We aren't forced to put this in a try-catch.
        // System.out.println(text.length()); 


        // --- CHECKED EXCEPTION (Compiler enforces handling) ---
        File file = new File("nonexistent.txt");
        
        // If we just write: FileReader fr = new FileReader(file);
        // The compiler throws an error: "Unhandled exception: FileNotFoundException"
        
        try {
            FileReader fr = new FileReader(file);
        } catch (IOException e) {
            System.out.println("File was not found. Please provide a valid file.");
        }
    }
}

Interview Questions

Q: Should custom business exceptions be checked or unchecked?
A: Historically, developers used checked exceptions for business logic errors. However, modern Java frameworks (like Spring) heavily favor unchecked exceptions (RuntimeException). Checked exceptions often clutter the codebase by forcing developers to write boilerplate throws declarations all the way up the call stack, even if the higher layers can’t do anything to fix the problem.

Q: What is the superclass of all Unchecked Exceptions?
A: java.lang.RuntimeException is the superclass of all unchecked exceptions. Any exception that inherits from RuntimeException (like NullPointerException, IllegalArgumentException, ArithmeticException) is exempt from the compiler’s check-or-declare requirement.