"SStory" <Th*******@TAKEOUTTHISSPAMBUSTERsofthome.net> wrote in message
news:eN****************@TK2MSFTNGP11.phx.gbl...
When I right a class, I am wondering what are the best practices for error
handling?
Do I try..catch and trap the error and if so what do I do with it?
Because most likely the class user will want to know the information in the
exception....
That being the case do I just not catch it and let the user of the class
catch it and get all the information?
I know I could catch it and throw my own, but I'd have to tell them the
same thing the original exception already has so I think what is the point?
Please give me some best practices advice on this.
If you're really writing a class library, the rules are a little more
strict. For a library designer you should validate all of your input
arguments and immediately throw an ArgumentException or
ArgumentNullException or ArgumentOutOfRangeException on invalid input. This
will prevent you throwing confusing exceptions later, like an unhelpful
NullReferenceException or IndexOutOfRangeException.
If your type is stateful, and your methods can only be called when the
object is in a certian state then you should check that and throw an
InvalidOperationException if the object is in the incorrect state (eg not
"open", or "conneced" or "initialized").
In addition you should document if a particular kind of exception is
especially likely to be thrown.
But these are really all examples of a general proposition. The exceptions
thrown by a class library should clearly indicate what really went wrong.
You shold never throw an InvalidCastException or a NullReferenceException,
but you shouldn't really catch them either. Rather you should structure
your code and validate your inputs so that these exceptions don't get thrown
in the first place.
You should catch and rethrow exceptions when either the type of the
exception is misleading, or you need to bundle information from that stack
level to make the exception meaningful. I find custom exceptions only
really usefull for bundling common state information into a thrown
exception. So if you find yourself concatenating the same kinds of
information into a thrown exception's error message, condisder adding your
own Exception subtype with instance fields to hold this information.
David