Exceptions, part 1
Exceptions are amongst the least understood functionality in both the .NET and Java world. This is the first article in a series of articles about exception. In this series, I will give my opinion about them.
Subclassing the base Exception
If I create a library or a piece of business logic, one of the first things I do is to create my own subclass of exception.
Why do I do that?
Why not simply use the exception classes provided by the framework (java.lang.Exception or System.Exception) with a descriptive string message?
Actually, there is a very good reason, which only showed itself a short while ago:
I was evaluating a java library, and I got a IOExceptions from using it.
Since it was an IOException, I assumed that the errors had something to do with the FileInputStream I constructed: an invalid filename, perhaps?
As it turned out (the description of the exception didn’t help me much in this specific case), the exception had nothing to do with my stream, or even with I/O: the library simply threw IOExceptions everywhere, both in places related and not relation to I/O.
If a custom exception (or even a custom subclass of IOException) was thrown, I would have known instantly not to search for my error in the stream, but in the library.
Also, I could have separated my java I/O error handling code from the error handling code of this library by writing something like:
try {
...
} catch (IOException ioe) {
// do i/o related error handling
} catch (LibraryException le) {
// do library related error handling
}
Instead, my error-handling code will look like this:
try {
...
} catch (IOException e) {
if (e.getMessage().equals("something") {
// do i/o related error handling
} else {
// do library related error handling
}
}
Which is both ugly and error-prone.