I was thinking a long time about doing this. Writing an opinion about runtime agains checked exceptions. I decided to do it, just to form my own opinion and start doing it consistent. Please do not start the debate here, it is just my opinion. I will point you to a number of resources that can help you form you own opinion.
The reason to introduce Checked Exceptions in java is to assure that people do something with exceptions. This is made sure by the compiler. However there are a lot of side effects to this theory. Bruce Eckel has a very good entry on his blog, I quote one of his sentences that sais it all:
When someone is trying to do something and you are constantly praddin them with annoyances, they will use the quickest device available to make those annoyances go away.
One of the anti patterns is born: catch (Exception e), swallowed exceptions.
A disadvantage of Checked Exceptions is all the code you must write or rethrowing exceptions. This way you throw exceptions in layers that do not belong there or you catch exceptions and throw a new other exception. And a new anti-pattern is born. Runtime exceptions just go up untill the main thread, or you can catch them if you can can do something about it. The important part, if you do nothing you will get an exception at the top, you are not tempted to do the catch Exception part.
The blog item of Tim McCune is also a very good article about exception handling. This article states a number of anti-patterns that you will find in your code. You do not have to agree on all the items, but you can learn a lot of them. Some rules of this website that I agree upon are:
- Either log an exception or rethrow it.
- Never throw java.lang.Exception
- Never add multiple exceptions to throws that propably are handed the same, use a super class instead
- Never throw an exception from a finally block
I also have some ideas of myself, I adhere to the following rules:
- Add important runtime exceptions to the throws clause of your method. Instead of this you can also document them in your javadoc. It is important to let the users of your class/interface know what kind of exceptions they can expect
- Use a good logging framework, agree upon the levels to use and make sure to log the exception if you catch one.
- From java 1.4 there are nested exceptions, use these if you want to wrap a checked exception in a runtime exception. You can also use a special wrapper. There is one in apache commons-lang. The utility class to use from this package is:http://jakarta.apache.org/commons/lang/api-release/org/apache/commons/lang/exception/ExceptionUtils.html
Of course this is not a very extensive post, but it does give an idea about how I feel about checked exceptions.