To Throw a Checked Exception or Not 6
I understand the concept behind “correctness” and the compulsion to throw checked exceptions by Java developers. It’s the only language that has a distinction between runtime exceptions and checked exceptions, and it has wreaked its havoc on the world. Consider the problem of finding a piece of data. For example, Location.find(String) would return a Location object that is related to the string that can be an ID, routing number, or name. The typical Java developer would then dutifully create a LocationNotFoundException and throw that any time find can’t return a result. That’s even more likely if the Location information is stored in a database. The alternative would be for Location to return null if it can’t find the object. So, let’s look at what might happen in some code:
// From an address object
Location getLocation()
{
Location location = null;
try
{
location = Location.find(routingNumber);
}
catch(LocationNotFoundException lnfe)
{
try
{
location = Location.find(addressName);
}
catch(LocationNotFoundException lnfe)
{}
}
return location;
}
There is so much extra crap in here that is required because of the fact the method throws an exception. All we want to do is try to find a location by a routing number, and then try looking up the location by name if the mapping hasn’t been made yet. Now, what if we didn’t have to worry about an exception?
// From an address object
Location getLocation()
{
Location location = Location.find(routingNumber);
if ( null == location )
{
location = Location.find(addressName);
}
return location;
}
Isn’t that so much cleaner? Sure, I could have let the method propogate the exception, but if the could assumes that no exception is thrown, it will never reach the second try. That’s why consistency, even if it is cumbersome, is important. There is a time and place for exceptions, but in many ways it would be more graceful to handle the error condition differently.
Now what about debugging? If a method returns null if it can’t find the result, what if the reason is because the database connection went down? Even if the thrown exception is the same, Java allows you to attach the exception that caused this one. The information is available. However, it is also my experience that many developers throw exceptions away. Did you see that in the first example? Logging helps, but in the long run, it is better to use unit tests to verify that everything behaves as expected.
