3. Wrapping exceptions

Checked exceptions seemed cool in theory, but turned out to be a huge frustration in practice.

Suppose you have a super popular method in your project. It is called from hundreds of places in your program. And you decide to add a new checked exception to it. And it may well be that this checked exception is really important and so special that only the main() method knows what to do if it is caught.

That means you'll have to add the checked exception to the throws clause of every method that calls your super popular method. As well as in the throws clause of all the methods that call those methods. And of the methods that call those methods.

As a result, the throws clauses of half of the methods in the project get a new checked exception. And of course your project is covered by tests, and now the tests don't compile. And now you have to edit the throws clauses in your tests as well.

And then all your code (all the changes in hundreds of files) will have to be reviewed by other programmers. And at this point we ask ourselves why we made we made so many bloody changes to the project? Day(s?) of work, and broken tests — all for the sake of adding one checked exception?

And of course, there are still problems related to inheritance and method overriding. The problems that come from checked exceptions are much larger than the benefit. The bottom line is that now few people love them and few people use them.

However, there is still a lot of code (including standard Java library code) that contains these checked exceptions. What is to be done with them? We can't ignore them, and we don't know how to handle them.

Java programmers proposed to wrap checked exceptions in RuntimeException. In other words, catch all the checked exceptions and then create unchecked exceptions (for example, RuntimeException) and throw them instead. Doing that looks something like this:

try
{
   // Code where a checked exception might occur
}
catch(Exception exp)
{
   throw new RuntimeException(exp);
}

It's not a very pretty solution, but there's nothing criminal here: the exception was simply stuffed inside a RuntimeException.

If desired, you can easily retrieve it from there. Example:

Code Note
try
{
   // Code where we wrap the checked exception
   // in a RuntimeException
}
catch(RuntimeException e)
{
   Throwable cause = e.getCause();
   if (cause instanceof Exception)
   {
      Exception exp = (Exception) cause;
      // Exception handling code goes here
   }
}







Get the exception stored inside the RuntimeException object. The cause variable maybe null

Determine its type and convert it to a checked exception type.