Thursday 15 October 2015

Checked vs Un Checked Exception

It is said that programmers should always avoid a Runtime exception (which is also known as unchecked exception)  and always handle a checked exception. Runtime exceptions are the exceptions like NullPointerException, ArrayIndexOutOfBound etc that extend to RuntimeException class. Whereas Checked exceptions are the exceptions  defined by user and that extend to Exception class. Examples of checked exceptions are FileNotFound exception, SQLException. But what is the exact difference?
The java compiler forces you to handle  a checked exception like FileNotFound exception which is not the case in RuntimeExceptions. 
Here is a simple illustraion:-

Define your own checked exception like the one below

File: SomethingWentWrongException.java
Definition:

public class SomethingWentWrongException extends Exception {
         

}

Now try to use the above exception class. 

File: ExceptionEperiment.java
Definition:

public class ExceptionExperimenter {
   public static void main(String[] args){
        doSomething();
    }

    private static void doSomething()  throws SomethingWentWrongException {
        throw new SomethingWentWrongException();
    }
}

Now compile these two classes. If you are using an IDE you will notice a compiler error highlight on the line where you are calling doSomething() method. The error message say "Unhandled exception : SomethingWentWrongException". If you are compiling using command line then you will get the same message. 

This is because the compiler forces you to handle a checked exception.

Now lets tweak the SomethingWentWrongException class by extending it to RuntimeException. See the tweak below:-

File: SomethingWentWrongException.java
Definition:

public class SomethingWentWrongException extends RuntimeException {
         

}

Now compile the classes. Notice the difference? This time the compiler didn't force you to handle the exception. I hope you understood the basic difference.

Over the time, usage of checked exception became a bad practice. If you see some frameworks like Spring and hibernate, the APIs designed in these frameworks don't throw checked exception. This is because there is unnecessary boilerplate code to handle the exception which affects the readability of the code. The idea behind not using a checked exception while designing your APIs is to let the user of your API decide weather he needs to handle it or not .