Monday, August 2, 2021

Checked vs Unchecked Exception in Java? Example

Checked and Unchecked Exception is two types of Exception exist in Java. Though there is no difference in functionality and you can very achieve the same thing with either checked Exception or Unchecked Exception, there is some difference on exception handling part. In this Java tutorial we will see what is checked and Unchecked Exception in Java, Examples of Checked and Unchecked Exception and most importantly we will learn when to use Checked Exception and when to use Unchecked Exception in Java and lastly we will see the difference between checked and unchecked exception to understand things better. 

By the way, this article is second in my post on Exception along with the difference between throw and throws in Java and improved Exception handling in Java 7 with Automatic resource management ARM and multi-catch block in JDK 7.

Difference between Checked vs Unchecked Exception in Java

Now, let's do deep dive on both checked and unchecked Exception classes in Java to understand the difference between them.


1. What is Checked Exception in Java?

Checked Exception vs Unchecked Exception in Java exampleChecked Exception in Java is all those Exception which requires being catches and handled during compile time. If Compiler doesn’t see try or catch block handling a Checked Exception, it throws Compilation error. Now Which Exception is checked Exception and Why Checked Exception are introduced in first place? All the Exception which are direct sub Class of Exception but not inherit RuntimeException are Checked Exception.

While doing File Programming in C++ I found that most of the time programmer forgets to close file descriptors , which often result in locking of file on OS level. Since Java is introduced after C++, designers of Java thought to ensure such mistakes are not allowed and resources opened are closed properly. 

To ensure this they introduced Checked Exception. If you see most of File IO related operation comes under IOException which is checked one. Though is a special scenario related to Checked Exception but you can generalize this as, where Java sees an opportunity of failure more, they ensure that programmer provide recovery strategy or at least handle those scenario gracefully.



Since a picture is worth 1000 words I have put together Exception hierarchy in mind map which clearly says which Exceptions are checked and which Exceptions are unchecked.

Difference between Checked and Unchecked Exception in Java


2. When to use Checked Exception in Java

Knowing Checked Exception is not that useful until you know how to use Checked Exception in Java. Java has often been criticized for its Checked Exception strategy, arguments given are that checked Exception adds a lot of boilerplate code and makes the whole class or function unreadable. 

Somewhat I agree with this and java also recognizes this by introducing improved Exception handling mechanism in Java7 but Checked Exception does have its real purpose. Following are some scenarios where I would prefer to use Checked Exception to ensure that Code is Robust and stable:



1) All Operation where chances of failure is more e.g. IO Operation, Database Access or Networking operation can be handled with Checked Exception.

2) When you know what to do (i.e. you have an alternative) when an Exception occurs, may be as part of the Business Process.

3) Checked Exception is a reminder by compiler to programmer to handle failure scenario.

3. Example of checked Exception in Java API 

Following are some Examples of Checked Exception in Java library:

IOException
DataAccessException
InvocationTargetException

4. What is an Unchecked Exception in Java?

Unchecked Exception in Java is those Exceptions whose handling is not verified during Compile time. Unchecked Exceptions mostly arise due to programming errors like accessing the method of a null object, accessing elements outside an array bonding, or invoking methods with illegal arguments. In Java, Unchecked Exception is a direct sub Class of RuntimeException. What is a major benefit of Unchecked Exception is that it doesn't reduce code readability and keeps the client code clean.

5. When to use UnCheckedException in Java?

A good strategy of Exception handling in Java is wrapping a checked Exception into UnCheckedException. Since most of the Database operation throws SQLException but it’s not good to let SQLException propagate from your DAO layer to up higher on business layer and client code provide exception handling you can handle SQLException in DAO layer and you can wrap the cause in a RuntimeException to propagate through client code. 

Also as I said earlier unchecked exceptions are mostly programming errors and to catch them is really hard until you do a load test with all possible input and scenarios. See these free Core Java online courses for more details. 




6. Difference between Checked and Unchecked Exception in Java

Now we have enough information to differentiate Checked Exception with Unchecked Exception:

1) Checked Exception is required to be handled by compile-time while Unchecked Exception doesn't.

2) Checked Exception is a direct sub-Class of Exception while Unchecked Exception are of RuntimeException.

3) CheckedException represents a scenario with a higher failure rate while UnCheckedException is mostly programming mistakes.

7. Example of unchecked Exception in Java API

Here are few examples of Unchecked Exception in Java library:
  • NullPointerException
  • ArrayIndexOutOfBound
  • IllegalArgumentException
  • IllegalStateException


8. Summary:
1. Both Checked and Unchecked Exception are handled using keyword try, catch, and finally.

2. In terms of Functionality Checked and Unchecked Exception are the same.

3. Checked Exception handling verified during compile time.

4. Unchecked Exception is mostly programming errors

5. JDK7 provides improved Exception handling code with catching multiple Exception in one catch block and reduce amount of boilerplate code required for exception handling in Java.


Related Java Tutorials

11 comments :

Mehmet Cirak said...

Good post. I use the same/similar rule of thumb when it comes to exceptions, and when in doubt go with runtime exception based on arguments presented by the Spring Framework team. Feels good to have someone else think the same way, almost like an affirmation :)

Niharika said...

One difference between Checked and UnChecked Exception is that checked Exception requires mandatory try catch or try finally block but unchecked Exception don't.

Another difference between Checked and UnChecked Exception is in where to use them. checked Exception should be use if you know how to recover from Exception while Unchecked Exception should be used for programming errors.

Gauri said...

Hello Javin, Can you please provide some guidance on proper use of checked Exception and RuntimeException in Java. Can you give me a scenario, where you chose to throw Exception or sub class of java.lang.Exception instead of unchecked exception or subclass or java.lang.RuntimeException ?

Anonymous said...

There is some discrepancy in the diagram. Error should be unchecked

Anonymous said...

I do not understand why "Since Java is introduced after C++, designers of Java thought to ensure such mistakes are not allowed and resources opened are closed properly." Checked exceptions have nothing in common with clearing resources.

Anonymous said...

All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
please read http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

Anonymous said...

Thanks very much for your blog and answers.
Please correct the following:
java.lang.Error and it's sub classes are also unchecked exceptions. Your diagram is misleading.
Thanks.

Anonymous said...

There is a question often asked in interviews :
If you can handle checked exception, then why not each exception is checked exception?why java have a concept of unchecked exception.

HITARTH said...

One more difference between checked and unchecked exception is that :-
Checked exception:- The program doesn't compile if there is an unhandled checked exception ....

Unchecked exception:- The program compiles successfully even though there is an unhandled unchecked exception in program code....

Anonymous said...

Question : In case of checked exceptions if we not handle or simply throws also JVM will handle means what? in case of unchecked exceptions JVM will not handle means where the difference will be there? as per my understanding in case of checked exceptions if throws JVM will close the opened resources and smooth execution will be happens and in case of unchecked exception JVM is not going to handle resource management or what?

javin paul said...

Hello @Anonymous, Sorry, didn't get your question? JVM doesn't handle any exception its user responsibility to handle error. In case of checked exception, compiler will warn you but throwing compile time error but in case of RuntimeException, compiler will not warn you either.

Post a Comment