grayscale photo of people standing near the wrecked vintage car

Exceptions in Java

Checked and Unchecked Exceptions

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of program’s instruction. Exceptions are categorized into two types; checked exceptions and uncheck exceptions.

Checked exceptions indicate exceptions which well-written applications can anticipate and recover from. Java requires us to take a precaution against checked exceptions, which is known as Catch or Specify Requirements. One approach is to enclose an operation which could throw a checked exception with try statement. The other approach is to have that operation enclosed in a method which specifies that it could throw a checked exception. Otherwise, they wouldn’t compile.

On the other hand, unchecked exceptions mean exceptions which we cannot anticipate and recover from. Unchecked exceptions are composed of errors and runtime exceptions. While errors are exceptions which stem from problems external to the application, runtime exceptions are ones that stem from the problems internal to the application such as logic errors.

The class hierarchy is as follows:

  • java.lang.Throwable class is inherited from java.lang.Exception class and java.lang.Error class.
  • java.lang.RuntimeException class inherits java.lang.Exception class.

Catching and Handling

A try-catch-finally statement ensures that operations described in the finally block is executed even if an unexpected exception occurs.
Therefore, it is used to make sure that I/O resources are closed.

A try-with-resources statement also achieves this as follows: try keyword is followed by the resources which implement java.lang.AutoClosable interface enclosed with parentheses.