Friday, December 5, 2008

Checked Exception Vs Unchecked Exception

How do you decide what type of Exception to throw? Should you throw a Checked Exception or Unchecked Exception? Well here are a few questions to consider whenever you come across such a situation which will help you make a better decision

1) Does your code have to handle the errors or report the error according to a specific custom error defined by your application?

2) Is the error recoverable ? Do you have an alternate way of recovering from the error?

3) Are you designing an API ?

If your answer to the above questions is "YES" then you definitely need to work with checked exceptions.Simply put Unchecked exceptions are generally used to determine programming errors or situations where it simply makes no sense to recover from an error situtation. Unchecked exceptions are also used when you are working with third party API's where you really have no control over them.

One more thing there are situations which will justify both scenarios in that case I generally follow this rule "When in doubt go with Unchecked Exceptions".

2 comments:

Chirag said...

I favour using unchecked exceptions for most of the situations.

This article describes the pros and cons of checked and unchecked exceptions pretty well.

Ajit Balan said...

Thanks bro :)