One man’s checked exception is another man’s run time exception

Recently, I was working on this project and I had just finished up the refactoring of it.  A colleague came over to review my code and he pointed out that there have always been a bunch of places that make remote calls and often fail in ways that are out of our control.  He wanted me to make sure we handle all of those situations.  The way this legacy code was written made that pretty difficult because these remote calls were made all over the place.

I realized that Java comes with a really good solution to this problem: Checked exceptions.  If you’re not familiar with checked exceptions, they are a way to force the code that calls a method to deal with the possibility that an error might occur.  Here’s an example:

In this case, FileNotFoundException  is a checked exception.  Because it’s a checked exception, my code is forced to deal with it or it will not compile.  On the other hand, the Integer  i  is null, but my code does not have to deal with that possibility when I call toString  on it.  This is called a run time exception because the error happens when I run my code (as opposed to when I compile it).

Continue reading