Checked and Unchecked Exceptions in Java

There are two types of exceptions in Java i.e. checked and unchecked exceptions. Below I have explained about these two exceptions with examples.

Checked and Unchecked Exceptions in Java
Image Source

Checked and Unchecked Exceptions in Java

Checked Exceptions

  • Those exceptions that are checked at compilation time are called checked exceptions.
  • Checked exception includes the classes that extend Throwable class except RuntimeException and Error.
  • Some examples of checked exceptions are:
    • InvocationTargetException
    • SQLException
    • ClassNotFoundException
    • IOException
  • If a method throws checked exceptions then it must handle them by try catch block or declare the exceptions by throws keyword.

 

Consider below example.

 

When you will run this program you will get following compilation error.

 

This error can be solved in two ways.

1. Using try catch block

We can handle the exception using try catch block in following way.

 

2. Using throws keyword

We can also handle exception using throws keyword in following way.

 

Unchecked Exceptions

  • The exceptions that are not checked at compilation time are called unchecked exceptions.
  • These exceptions occur at run time due to some bad data. For example if a program tries to divide a number with zero then it will cause ArithmeticException and result in program termination if not handled.
  • Unchecked exception includes the classes that extend RuntimeExcpetion class.
  • Some examples of unchecked exceptions are:
    • IllegalArgumentException
    • NullPointerException
    • ArithmeticException
    • ArrayIndexOutOfBoundsException
  • Although these exceptions are not checked at compilation time but we must handle them properly.

 

Consider below example.

 

The above program will compile perfectly but will show following error when you will run it.

 

We can handle it using try catch block.

 

Comment below if you found anything incorrect or have queries related to above tutorial for checked and unchecked exceptions in java.

1 thought on “Checked and Unchecked Exceptions in Java”

Leave a Comment

Your email address will not be published. Required fields are marked *