Java > Core Java > Exception Handling > Checked vs Unchecked Exceptions

Checked vs. Unchecked Exceptions in Java

This example demonstrates the difference between checked and unchecked exceptions in Java. Checked exceptions must be caught or declared to be thrown, while unchecked exceptions are not enforced by the compiler.

Checked Exception Example: IOException

This code tries to read from a file that might not exist. FileReader and BufferedReader throw IOException, which is a checked exception. The compiler forces us to either catch this exception using a try-catch block or declare that the main method throws it using throws IOException. If we remove the try-catch block, the code will not compile.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {

    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("nonexistent_file.txt"));
            String line = br.readLine();
            while (line != null) {
                System.out.println(line);
                line = br.readLine();
            }
            br.close();
        } catch (IOException e) {
            System.err.println("An IOException occurred: " + e.getMessage());
        }
    }
}

Unchecked Exception Example: NullPointerException

This code attempts to call the length() method on a null String, which results in a NullPointerException. NullPointerException is an unchecked exception, which means the compiler does not require us to handle it. Although we've included a try-catch block here, it's not strictly necessary for the code to compile. The program will compile and potentially throw the exception at runtime if the try-catch is not present.

public class UncheckedExceptionExample {

    public static void main(String[] args) {
        String str = null;
        try {
            System.out.println(str.length()); // This will throw a NullPointerException
        } catch (NullPointerException e) {
            System.err.println("A NullPointerException occurred: " + e.getMessage());
        }

        System.out.println("Program continues after potential exception.");
    }
}

Concepts Behind the Snippet

Checked exceptions are exceptions that the compiler forces you to handle or declare in the method signature. Unchecked exceptions are not checked at compile time and usually result from programming errors.

Real-Life Use Case

  • Checked Exceptions: Dealing with file operations, network connections, or database interactions, where external factors can cause failures that the program must gracefully handle.
  • Unchecked Exceptions: Handling situations like incorrect input from a user (resulting in an IllegalArgumentException) or unexpected null values (resulting in a NullPointerException).

Best Practices

  • Use checked exceptions when the caller can reasonably recover from the exception.
  • Use unchecked exceptions for programming errors or conditions that are unlikely to be recoverable.
  • Avoid catching Exception unless you really need to handle all possible exceptions. Catch more specific exceptions instead.

Interview Tip

Be prepared to explain the difference between checked and unchecked exceptions, give examples of each, and discuss when to use each type. Also, be familiar with common exception types like IOException, NullPointerException, IllegalArgumentException, and IndexOutOfBoundsException.

When to Use Them

  • Checked Exceptions: Use when a failure is an expected part of the program's execution, and the caller should be prepared to handle it (e.g., file not found).
  • Unchecked Exceptions: Use for errors that are usually due to programming mistakes (e.g., accessing an array out of bounds).

Alternatives

  • Instead of throwing exceptions for recoverable errors, consider returning a special value (e.g., null or an error code). However, this can lead to less explicit error handling.
  • Use a Result object or Optional to encapsulate success or failure states.

Pros and Cons

Checked Exceptions:

  • Pros: Force developers to handle potential errors, leading to more robust code.
  • Cons: Can lead to verbose and cumbersome code if not used carefully.

Unchecked Exceptions:
  • Pros: Less verbose code, easier to implement.
  • Cons: Errors may not be caught until runtime, potentially leading to unexpected crashes.

FAQ

  • What is the difference between Error and Exception?

    Errors are typically unrecoverable problems that a program cannot handle (e.g., OutOfMemoryError). Exceptions are conditions that a program can potentially catch and recover from.
  • What are some common checked exceptions?

    Common checked exceptions include IOException, SQLException, and ClassNotFoundException.
  • What are some common unchecked exceptions?

    Common unchecked exceptions include NullPointerException, IllegalArgumentException, IndexOutOfBoundsException, and ArithmeticException.
  • Should I catch every exception?

    No. You should only catch exceptions that you can reasonably handle. Catching and ignoring exceptions can mask underlying problems and make debugging difficult.