Checked vs Unchecked Exceptions
Java exceptions are categorized into checked (must be declared or handled) and unchecked (do not require explicit handling or declaration), influencing how errors are managed.
Checked: extends Exception (not RuntimeException)
Unchecked: extends RuntimeException or ErrorThis static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Java exceptions are categorized into checked (must be declared or handled) and unchecked (do not require explicit handling or declaration), influencing how errors are managed.
Java distinguishes between two main types of exceptions: checked and unchecked. Checked exceptions are subclasses of `java.lang.Exception` (but not `RuntimeException`). The compiler enforces that methods throwing checked exceptions must either declare them in their `throws` clause or handle them using a `try-catch` block. This forces developers to acknowledge and plan for potential recovery from these errors, typically for conditions that are external to the program's logic but might occur (e.g., `IOException`, `SQLException`). Unchecked exceptions are subclasses of `java.lang.RuntimeException` or `java.lang.Error`. The compiler does not require them to be declared or caught. `RuntimeException`s usually indicate programming errors (e.g., `NullPointerException`, `ArrayIndexOutOfBoundsException`, `IllegalArgumentException`), while `Error`s represent serious, unrecoverable system problems (e.g., `OutOfMemoryError`). The choice between checked and unchecked depends on the recoverability of the error: use checked for recoverable conditions where the caller can take corrective action, and unchecked for programming bugs or situations where the application cannot reasonably recover. Best practices suggest favoring unchecked exceptions for API design when the error is a client-side programming mistake or an unrecoverable condition, to avoid cluttering method signatures with `throws` clauses for errors that cannot be meaningfully handled by callers.
Quick reference
Syntax
Checked: extends Exception (not RuntimeException)
Unchecked: extends RuntimeException or Error
See it in practice
Examples
Handling a checked exception (IOException)
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent.txt"); // Throws checked IOException
System.out.println("File opened.");
reader.close();
} catch (IOException e) {
System.err.println("Caught a checked exception: " + e.getMessage());
}
}
}Caught a checked exception: nonexistent.txt (No such file or directory)
The `FileReader` constructor throws a checked `IOException`. The compiler requires it to be caught (as shown) or declared with `throws` in the `main` method signature.
Handling an unchecked exception (NullPointerException)
public class UncheckedExceptionExample {
public static void main(String[] args) {
String text = null;
try {
System.out.println(text.length()); // Throws unchecked NullPointerException
} catch (NullPointerException e) {
System.err.println("Caught an unchecked exception: " + e.getMessage());
}
System.out.println("Program continues.");
}
}Caught an unchecked exception: Cannot invoke "String.length()" because "text" is null Program continues.
Accessing a method on a `null` reference throws an unchecked `NullPointerException`. The compiler does not force handling, but it's good practice to catch it if recovery is possible.
Custom checked vs. unchecked exception design
class MyCheckedException extends Exception { public MyCheckedException(String msg) { super(msg); } }
class MyUncheckedException extends RuntimeException { public MyUncheckedException(String msg) { super(msg); } }
public class CustomExceptionDesign {
public void performCheckedOperation() throws MyCheckedException {
// This operation might fail due to external factors, caller can recover
if (Math.random() < 0.5) throw new MyCheckedException("External resource unavailable");
System.out.println("Checked operation successful.");
}
public void performUncheckedOperation() {
// This operation might fail due to a programming error, caller likely can't recover
if (Math.random() < 0.5) throw new MyUncheckedException("Invalid internal state");
System.out.println("Unchecked operation successful.");
}
public static void main(String[] args) {
CustomExceptionDesign app = new CustomExceptionDesign();
try {
app.performCheckedOperation(); // Must handle MyCheckedException
} catch (MyCheckedException e) {
System.err.println("Handled checked: " + e.getMessage());
}
// app.performUncheckedOperation(); // No explicit catch required
try {
app.performUncheckedOperation(); // Can optionally catch unchecked
} catch (MyUncheckedException e) {
System.err.println("Handled unchecked: " + e.getMessage());
}
}
}Checked operation successful. Unchecked operation successful. OR Handled checked: External resource unavailable Handled unchecked: Invalid internal state
Demonstrates defining custom checked (`extends Exception`) and unchecked (`extends RuntimeException`) exceptions, illustrating when each type is appropriate based on recoverability.
Debug faster
Common Errors
Compile-time Error
Cause: Throwing a checked exception without declaring it in the method's `throws` clause or handling it with `try-catch`.
Fix: Add `throws ExceptionType` to the method signature or wrap the code in a `try-catch` block.
import java.io.IOException;
public class Error {
public void readFile() { // Compile-time error: unreported exception IOException
// throw new IOException("Error");
}
}Bad Design / Over-catching
Cause: Catching `RuntimeException`s or `Error`s too broadly, masking programming bugs or unrecoverable system issues.
Fix: Only catch unchecked exceptions if you can genuinely recover or log them meaningfully. Avoid catching `Error`s. Let programming bugs propagate to crash the application, indicating a need for code fix.
try {
// ... code that might throw NullPointerException
} catch (RuntimeException e) { // Catches too broadly, might hide bugs
System.err.println("Something went wrong: " + e.getMessage());
}Runtime support
Compatibility
Source: Oracle Java Documentation
Common questions
Frequently Asked Questions
Java exceptions are categorized into checked (must be declared or handled) and unchecked (do not require explicit handling or declaration), influencing how errors are managed.
Compile-time Error: Add `throws ExceptionType` to the method signature or wrap the code in a `try-catch` block. Bad Design / Over-catching: Only catch unchecked exceptions if you can genuinely recover or log them meaningfully. Avoid catching `Error`s. Let programming bugs propagate to crash the application, indicating a need for code fix.