Checked-- vs Unchecked Exceptions

Exceptions can be checked or unchecked. Unchecked exceptions, like null pointer references or a division by zero don't need to be declared and handled by the programmer. The idea is, that these exceptions never happen in a correct program as they indicate a faulty program.

In contrast, checked exceptions have to be declared in the signature of the methods using the throws keyword and need to be handled by the method directly using a try-catch block or are delegated to the caller of the method using the throws keyword. Unchecked exceptions are out of the control of the programmer. For example, if one tries to read from a file that the user just deleted, or if a network error occurs. The program has to able to deal with these kind of situations. That is why Java forces you to either deal with the exception or declare them in the method.

A programer can define their own checked, as well as unchecked exceptions. Both checked-- and unchecked exceptions are subclasses of Throwable. A checked exception is defined by subclassing from Exception and an unchecked exception as a subclass of Error or Throwable.

For example, the addBook operation of the library could be called from the administrator or from the normal user. In our case, if the addBook operation is called when the administrator is not logged in, then an OperationNotAllowedException should be thrown. Also, in this case we want to have OperationNotAllowedException to be a checked exception. A new exception class is defined as follows

public class OperationNotAllowedException extends Exception {
  public OperationNotAllowedException(String errorMsg) {
    super(errorMsg);
  }
}
and then we case that exception in addBook as follows:
public void addBook(Book book) 
   throws OperationNotAllowedException {
  if (!adminLoggedIn()) 
    throw new OperationNotAllowedException(...);
  ...
}


On to Handling Exceptions Part of User-defined Exceptions
Hubert Baumeister
April 23, 2018