Tuesday, January 24, 2017

Why Checked Exception exists in Java when we have Runtime Exception in our bucket?

Have you ever thought Why Checked Exception exists in Java when we have Runtime Exception to convey exceptional cases in our program? There must be a pretty good reason behind it? Have you ever tried to find it out?

Today we would provide you a small overview about Checked Exception then we directly jump on answering our topic of interest today i.e. Why Checked Exception exists in Java?

Checked Exception

 The Exception (most commonly occurred exception) which are checked by a compiler for smooth execution of the program at runtime are called Checked Exception. In the case of a Checked Exception, the compiler will check whether we are handling the exception if not then we will get the compiler error that means checked exceptions are subject to the Catch or Specify Requirement. 
  • Checked exceptions have to be declared on a method signature, or handled.
  • All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. eg. FileNotFoundException
Now we have some idea about the Checked Exception. Let's find out the reason.

One liner answer - Forcing developers to handle most common problems in early stage(compile time) to make our code robust and reliable.

Explanation:

 For making our code robust and reliable, designers/authors of the Java already have decided for us what most common problems we might face during the execution of our program at runtime. They deliberately forced us to handle these types of problem as early as possible so that we could perform a proper analysis of all the gray areas and strange edge cases while developing our codes as opposed to getting an error in runtime and then again refactoring our code accordingly. It saves a lot of rework and also adding the error handling code at maintenance phase/later stage is expensive. That's why authors of the Java have introduced the concepts of checked exception in Java.

Thank you for reading this article. Hope you would like it. If you have any suggestion or have any question do let me know in the comment box. Happy Learning!!😌

Note: Actually this question was originally answered by me in Quora.Here is the link to that question.

No comments:

Post a Comment