Information Technology Reference
In-Depth Information
throw ;
}
}
finally
{
CleanupResources();
}
}
That's far less appealing than using multiple catch clauses. It's very brit-
tle code: If you change the name of a routine, it's broken. If you move the
error-generating calls into a shared utility function, it's broken. The deeper
into the call stack that an exception is generated, the more fragile this kind
of construct becomes.
Before going any deeper into this topic, let me add two disclaimers. First,
exceptions are not for every error condition you encounter. There are no
firm guidelines, but I prefer throwing exceptions for error conditions that
cause long-lasting problems if they are not handled or reported immedi-
ately. For example, data integrity errors in a database should generate an
exception. The problem only gets bigger if it is ignored. Failure to correctly
write the user's window location preferences is not likely to cause far-
reaching consequences. A return code indicating the failure is sufficient.
Second, writing a throw statement does not mean it's time to create a new
exception class. My recommendation on creating more rather than fewer
exception classes comes from normal human nature: People seem to grav-
itate to overusing System.Exception anytime they throw an exception. That
provides the least amount of helpful information to the calling code.
Instead, think through and create the necessary exceptions classes to enable
calling code to understand the cause and provide the best chance of recovery.
I'll say it again: The reason for different exception classes—in fact, the only
reason—is to make it easier to take different actions when your users write
catch handlers. Look for those error conditions that might be candidates
for some kind of recovery action and create specific exception classes to
handle those actions. Can your application recover from missing files and
directories? Can it recover from inadequate security privileges? What about
missing network resources? Create new exception classes when you encounter
errors that might lead to different actions and recovery mechanisms.
So now you are creating your own exception classes. You do have very spe-
cific responsibilities when you create a new exception class. Your exception
 
Search WWH ::




Custom Search