Thursday, January 22, 2009

Checked Vs Unchecked Exceptions

In Java, there are 2 kinds of Exception:

Unchecked Exceptions which indicate some sort of programming error on the part of developer. Unchecked Exceptions are usually subclasses of RuntimeException class. Examples include: 
 --- NullPointerException (which is usually thrown when method is              invoked on a null object)
 --- DivideByZeroException (thrown when divide by zero happens in        your code)
 --- IllegalArgumentException (usually thrown when invalid argument        is passed to a method)
 --- ArrayIndexOutOfBoundsException (thrown when you try to access         array index beyond the memory allocated to it)
 --- ArithmeticException
 --- RuntimeException
If your methods throw an unchecked exception, then your method need not specify it as a part of its API i.e no need to write all the exceptions it throws using "throws" clause.

Checked Exceptions on the other hand, specifies conditions that are not due to human errors but due to conditions that are not in programmer's control. These include conditions such as database errors, network failures, file not found when searching or performing some operation on it. Examples include:
 --- FileNotFoundException
 --- SQLException
 --- PersistenceException
On the other hand, if your code throws any checked conditions, then either you must handle it or specify it using "throws" clause else your program will give compile-time error. 

Checked Vs Unchecked
Use Checked Exception in your code when you Client code (code that calls your code) is capable of dealing with the Exception and have ample knowledge why that Exception occurred in the first place and how to do away with it. 
Otherwise, it is always preferable to use Unchecked Exceptions since then the Client code is not forced to handle it and can choose to ignore it. Though that would not solve the problem and the exception would travel high up in hierarchy of function calls and perhaps finally encountered by the JVM, but at least the Client code is saved from the hassle of dealing with Exceptions that they don't know about it.
Let's take an example. Suppose we have a method throwing an SQLException:
The client code would never come to know that why this SQLException occurred, as it has no knowledge of underlying business logic and internal database design. Thus client is unable to handle the exception, so its always better to not force a client to handle an exception he do not know about.

Articles Worth Reading:

No comments: