Exception HandlingJava Interview Questions

Checked Vs Unchecked exceptions

Posted On
Posted By admin

In this blog post, I will be explaining the difference between checked and unchecked exceptions.

Checked exceptions

Checked exceptions are those scenarios which can be pre-determined but not prevented. So, during the application design, the developer can anticipate that the program might run into such an exception. However, the programmer can do nothing to prevent these exceptions. So the only course of action is to handle the exception. So in case the code is capable of throwing some checked exception, the compiler will cause a compilation error if the exception is not handled.

 

Unchecked exceptions

Unchecked exceptions are caused either due to programming mistakes or due to hardware failure or some other system error. Because the programmer cannot anticipate them, the compiler does not require you to track unchecked exceptions.

Consider the following diagram:

exception hierarchy

 

The boxes in blue represent unchecked exceptions, while the ones in pink represent the checked exceptions.

The Throwable class is at the top of the exception hierarchy. It has two sub classes, Exception and Error. Exception has an important sub-class, the RuntimeException.  These represent exceptions that occur due to some programming mistakes like referencing a null value, dividing by 0, etc. These are unchecked exceptions.

There are also other sub-classes on the Exception class. These represent programming errors that can be anticipated but not prevented and so these are checked exceptions. The diagram above shows IOException and SQLException. In addition, there are several other checked exceptions. You can check them out here.

Finally, The Error class is a sub-class of Throwable. It represents errors that represent hardware or system failure. Since such errors cannot be anticipated, these are also unchecked exceptions.

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment