In Java, exceptions are broadly categorized into checked and unchecked exceptions. Here’s the distinction:

Checked Exceptions

  1. Definition: Checked exceptions are exceptions that are checked at compile time. The compiler enforces that these exceptions must be either handled using a try-catch block or declared in the method signature using the throws keyword.
  2. Examples:
    • IOException
    • SQLException
    • ClassNotFoundException
  3. Use Case: These exceptions usually represent conditions that are expected to happen in the application’s environment but are beyond the program’s control (e.g., missing files, failed network connections).
  4. Handling: You must handle or declare them, as the compiler won’t let the program compile otherwise.

    public void readFile(String filePath) throws IOException {
        FileReader reader = new FileReader(filePath); // Checked exception
    }
    

Unchecked Exceptions

  1. Definition: Unchecked exceptions are exceptions that are not checked at compile time. They are typically programming errors or runtime conditions that could be avoided with proper logic.
  2. Examples:
    • NullPointerException
    • ArrayIndexOutOfBoundsException
    • ArithmeticException
  3. Use Case: These usually indicate programming bugs or logical errors (e.g., accessing an array out of bounds or dividing by zero).
  4. Handling: The compiler doesn’t require handling them explicitly, but it’s good practice to handle or avoid them through robust coding.

    public void divideNumbers(int a, int b) {
        int result = a / b; // Unchecked exception if b is 0
    }
    

Key Differences

Aspect Checked Exceptions Unchecked Exceptions
Compile-Time Check Checked by the compiler. Not checked by the compiler.
Handling Requirement Must be handled or declared in the method signature. Handling is optional.
Origin Represents external, recoverable issues. Represents programming or logical errors.
Hierarchy Subclasses of Exception (but not RuntimeException). Subclasses of RuntimeException.

Best Practices

  • Use checked exceptions for conditions the program can recover from or handle gracefully.
  • Use unchecked exceptions for programmer errors, such as invalid arguments or logic flaws.
  • Avoid overusing checked exceptions, as they can clutter method signatures and reduce code readability.