Difference between checked and unchecked exception in java

In this post, we will see difference between checked and unchecked exception in java. It is important question regarding exceptional handling.

What is Exception?

Exception is unwanted situation or condition while execution of the program. If you do not handle exception correctly, it may cause program to terminate abnormally.

What is checked exception?

Checked exceptions are those exceptions which are checked at compile. If you do not handle them , you will get compilation error.
Lets understand with the help of example:
if you do not handle checked exception , you will get compilation error as below:

Add leading zeros to Integer on left

so there are two options two solve above compilation error.
Using try and catch block:
you can put error code prone in try block and catch the exception in catch block.

Example:

As you see, we have put error prone code in try block and various exceptions in catch block. Using throws : You can use throws keyword to handle exceptions.
As you can see , we have used throws keyword to handle the exception.

What is unchecked exception?

Unchecked exceptions are those exceptions which are not checked at compile time. Java won’t complain if you do not handle the exception.

Example:

When you run above program, you will get below exception:

Another example:

When you run above program, you will get below exception:

You can go through core java interview questions for beginners and experienced  and Exception handling interview questions for more such questions.

Was this post helpful?

Leave a Reply

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