Java Checked Exceptions vs Unchecked Exceptions

In Java, there are two types of exceptions: checked exceptions and unchecked exceptions.

Checked exceptions are those that the Java compiler forces you to handle or declare in a throws clause. These are exceptions that are checked at compile-time. Examples of checked exceptions include:

  • IOException: An exception that occurs when an input/output operation fails.
  • SQLException: An exception that occurs when there is an error accessing a database.

Here is an example of how to handle a checked exception:

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    try {
      FileInputStream fis = new FileInputStream("file.txt");
      // Some code here
      fis.close();
    } catch (IOException e) {
      System.out.println("An error occurred while reading the file.");
    }
  }
}

Unchecked exceptions, on the other hand, are not checked at compile-time. These are exceptions that are typically related to programming errors and are not expected to be handled by the program. Examples of unchecked exceptions include:

  • NullPointerException: An exception that occurs when you try to access a null object reference.
  • ArrayIndexOutOfBoundsException: An exception that occurs when you try to access an array element with an index that is out of bounds.

Here is an example of an unchecked exception:

public class Main {
  public static void main(String[] args) {
    int[] numbers = new int[5];
    numbers[10] = 100; // This will throw an ArrayIndexOutOfBoundsException
  }
}

It is generally recommended to handle checked exceptions, as they indicate a failure that the program should be prepared to handle. Unchecked exceptions, on the other hand, are typically not handled, as they indicate a programming error that should be fixed.