Vivek Agarwal’s Portal/Java Blog

An IBM Gold Consultant’s weblog about IBM, Lotus, WebSphere, J2EE, IT Processes, and other IT technologies

Posts Tagged ‘Checked Exceptions’

A controversial topic – exception handling approach …

Posted by Vivek Agarwal on April 27, 2010

Recently a client asked me to put together a short write-up on my preferred Java exception handling approach, and I figured I could blog about it as it has been a WHILE since I wrote anything on my blog! Now exception handling is one of those controversial topics that has the Java world split on checked/unchecked exceptions, and I certainly have an opinion about it. So here come my opinions! 🙂

  • Prefer unchecked versus checked exceptions in general

More often than not, clients are not in a position to handle exceptions, and either end up declaring all checked exceptions in their “throws” clause, or catching them generically and converting them into one “throws Exception” clause, or catching and converting them into a single “throws CustomCheckedException” clause. In none of these scenarios, do checked exceptions lend additional value. Checked exceptions do introduce some “versionability” issues – an earlier version of a method throws exceptions A and B, and now when you add new functionality to this method, it can encounter exception C which it cannot handle either; since checked exceptions are part of the interface, this method should not throw a checked exception C or else it breaks its contract with existing clients. Now you are stuck either converting C into an unchecked exception or modifying all clients – neither of these is a good option. Additionally with checked exceptions you can run into issues with needing to throw many exceptions because you cannot handle them within the method you are writing; once you get to a client that calls 3-4 methods each of which throw 3-4 exceptions each, you now have a client method that potentially needs to throw 12-15 exceptions – not good!

In general, most clients are unable to deal with exceptions, and hence it is preferable to make exceptions unchecked so that you do not require your clients to check for each exception. The client can choose to handle the exceptions that it knows how to handle.
  • If we encounter a checked exception in any code that we write, if we cannot handle the exception, we should in general convert the checked exception(s) from other libraries or base java libraries into an unchecked custom exception. Read the rest of this entry »

Posted in Java | Tagged: , , , , | 3 Comments »