Checked/Unchecked Exceptions

There are two types of exceptions in Java: Checked Exceptions, Unchecked Exceptions

Any exception extended from Error or RuntimeException is an Unchecked Exception.
Any exception extended from Exception (except RuntimeException) is a Checked Exception.

Java Checked Unchecked Exceptions

Unchecked Exceptions are also known as Runtime Exceptions, because these exceptions are not checked at compile time.

public void foo() {
  FileReader reader = new FileReader("./data.txt");
}

FileReader constructor in the code above throws FileNotFoundException. FileNotFoundException is a checked exception. So we should either handle the exception inside try/catch block or we should declare the foo method as throwing FileNotFoundException. Otherwise compiler displays the following error message.

Java Checked Exception

Two possible ways to fix the problem are shown below.

public void foo() throws FileNotFoundException {
  FileReader reader = new FileReader("./data.txt");
}
public void foo() {
  try {
    FileReader reader = new FileReader("./data.txt");
  } catch (FileNotFoundException e) {
  // TODO handle FileNotFoundException
  }
}

Now, examine the sample code below. It throws NullPointerException on line 3. However, compiler doesn’t warn us about this exception. We don’t need to declare the foo method as throwing NullPointerException or handle this exception in a try/catch block, because NullPointerException is an Unchecked Exception.

public void foo() {
  String choice = null;
  if (choice.equals("2")) {
    System.out.println("You selected second choice");
  }
}
SHARE