A look on Checked and Unchecked exception in Java

This is the one of the topic that the Java interviewers target,

1) What is checked and unchecked exception? – this is fine. simple.

2) what is the difference between Error and Exception?

3) Why the unchecked exception not necessary to be caught?

As we know, Java comes with some hierarchy, where, The parent of all exceptions is ‘Throwable’.  ‘Throwable’ class has 2 child, which is ‘Exception’ and ‘Error’.

All the exceptions that comes under the ‘Exception’ are called as Checked Exception, excluding the class ‘RuntimeException’ which is also subclass of ‘Exception’ class.

The subclasses that comes under ‘RuntimeException’ are called as Unchecked Exception.  Even the class ‘Error’ and its subclasses are also said to be unchecked exceptions. Errors and runtime exceptions are collectively known as unchecked exceptions.

But first, what is Checked Exception?

Checked Exceptions are the abnormal situation (an event that disturbs the normal flow, called as exception in general) that occurs within the application, where the well-written program should forecast and recover from.  For example, we have a program that prompt the user for filename and based on the user input, the program searches for the file in the filesystem.  If the file successfully found, we have no issue.  If the compiler or JVM does not able to find the file, the ‘FileReader’ constructor throws java.io.FileNotFoundException.   A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

Java Specification have “handle or declare” rule, that is, either catch the exception or declare it using ‘throws’ in the method signature so that someone can handle. This rule applies for all the exceptions that are subclasses of ‘Exception’ class.  Why? because it is certain that “bad things could happen”.  For example, while JVM tries to connect to the external file in the filesystem, anything could happen due to OS malfunction. It is certain.  These kind of exceptions must be “checked” and compiler forces us to do either you handle or declare so that the caller can handle.

What is Unchecked Exception?

‘RuntimeException’ and its subclasses and ‘Error’ and its subclasses are comes under Unchecked Exception, which compiler does not expect the programmer to catch.  The Java rule “handle or declare” rule does not apply over to the unchecked exception.  Although we can throw or catch. But not recommended.

Why ‘RuntimeException’ and ‘Error’ is not necessary to be caught?

Runtime exception occurs due to programming error.  Due to bad programming.   so it’s better to let the program crash right away.  It must be fixed by the programmer.  Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program’s clarity. Thus, the compiler does not require that you catch or specify runtime exceptions.  Compiler could not able to forecast or recover from.

I have a method which takes string argument and I am passing that to FileReader constructor. If someone passes ‘null’ string to my method, the FileReader constructor throws NullPointerException.  It is the programmer responsibility to handle this situation, to have a null check before passing to FileReader constructor. Here compiler could not forecast during compile-time and say “hey, there is a possibility that someone can pass null argument”.

Now coming on ‘Error’, which is again an abnormal situation or conditions that are external to the application or occur externally, and that the application usually cannot anticipate or recover from. Objects of type ‘Error’ are not ‘Exception’ objects, although do represent exceptional conditions. Thus both ‘Error’ and ‘Exception’ share a common superclass called ‘Throwable’.  Because, both can be thrown using the ‘throws’ keyword. 

You are not required to handle Error as like ‘RuntimeException’s.  Because, tell me, what an application or program will do when it encounters ‘OutOfMemoryError’, for example??  As a programmer, I don’t know what to do.  Can I say, “hey JVM, call the garbage collector or increase the memory size???”, Can we say?  It happens while in the hand of JVM and out of user application or program.  The JAVA specification does not recommend to handle these Errors.

What about user defined Exceptions? 

User defined exceptions are created by extending “Exception’ or ‘RunttimeException’.  How to decide that?

How to decide my exception to be Checked or Unchecked?

1. If a client can reasonably be expected to recover from an exception, make it a checked exception.

2. If a client cannot do anything to recover from the exception, make it an unchecked exception.

 I believe that every method should list, in its throws clause, what exceptions it throws (checked and runtime). This way it is clear to the user what to expect out of the method. Adequate JavaDoc explaining why each of the exceptions may be thrown is also very useful.

Since runtime exceptions can simply “bubble up” the stack, to either somebody who can handle the exception or to a catch-all, you only have to deal with the exception in one place. This reduces the amount of code you have to write, and reduces of number of places a bug can creep in. It also saves methods from having to catch or re-throw exceptions that they can’t recover from.

I think checked exceptions do still serve a purpose. I believe checked exceptions should be thrown when the caller is expected to handle the exception. For example, imagine you have an object that only does one thing: write data to a database.

public class DataWriter {

public void updateRowInFile(MyDataObject theData) throws DatabaseConnectionException, FileNotFoundException{

// Make the DB call to fetch the row and write the same in a file

} }


Let’s say it throws two exceptions, DatabaseConnectionException and FileNotFoundException. Of these two, I would say that the FileNotFoundException could be handled by the caller. Maybe the caller will read the row from databse, and write it into a file. Maybe the calling code can handle this automatically. Either way, it’s recoverable. So, I might make this a checked exception, forcing the caller to handle it. However, the DatabaseConnectionException is a bit trickier. The caller of updateRowInFile() may not know how to initialize a new database connection, or how to clean up an abandoned connection. I would probably make this exception a runtime exception, and let it propagate up to the top of the stack. This way, we could either show the user a general error message saying that the operation could not be completed (asking them to retry) or try to clean up the first attempt and re-try the operation for a second time automatically. The beauty about this is that this exception can be caught and handled, just like a checked exception, at any layer in the stack. So the layer that knows how to recover from the exception can catch it, and take the necessary action.









Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: