Sobes.tech
Junior — Senior

Differences between checked and unchecked exceptions in Java

livecode

Task condition

The example declares two custom exceptions: CheckedException, inheriting from Exception, and UncheckedException, inheriting from RuntimeException. When attempting to execute throw new CheckedException();, the compiler issues an error because a checked exception must either be handled in a try‑catch block or declared in the method signature with throws. To fix the error, you need to add throws CheckedException to the method declaration or wrap the call in a try { ... } catch (CheckedException e) { ... } block. The unchecked exception UncheckedException does not require such handling by the compiler.

public class JetbulbInterview {
    public static void main(String[] args) {
        // example method calls
        try {
            raiseChecked();
        } catch (CheckedException e) {
            System.out.println("Caught checked exception");
        }
        raiseUnchecked();
    }

    static void raiseChecked() throws CheckedException {
        throw new CheckedException();
    }

    static void raiseUnchecked() {
        throw new UncheckedException();
    }
}

class CheckedException extends Exception {}

class UncheckedException extends RuntimeException {}