Checked and unchecked exceptions

  • Eclipse: Oxygen
  • Java: 1.8

In Java, there are two types of exceptions:

  1. Checked exceptions
  2. Unchecked exceptions.

Java makes this division of exceptions depending on the level of importance of the exception. The checked exceptions are handled by the java compiler itself and the unchecked exception are handled by the user (not mandatory) in case of occurrence of such exceptions.

If any code within a method throws a checked exception, then the method must handle the exception or must specify the exception using the keyword throws.

For example, consider the following Java program we make use of FileReader class object and initialize it.  The program is not compiled, because the main function uses FileReader() and FileReader() throws a checked exception FileNotFoundException.

To fix the above program, we need to specify the list of exceptions using throws, or we need to use a try-catch block. We have used try and catch block in the following program.

Unchecked exceptions are not checked at compile time. All exceptions are disabled, so the compiler does not force them to handle or specify the exception. This is handled by the user (not mandatory) in case of the occurrence of such exceptions.

Consider the following Java program. It compiles well but throws ArithmeticException when it runs. The compiler allows you to compile because ArithmeticException is an unchecked or runtime exception.

Contributed by Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu