Catch most derived exceptions?
In .NET, when catching exceptions, should I always catch derived exceptions (so not ArgumentException but the derived types)?
Also:
If I am asked to use error codes, would this be in the constructor like so?:
throw new Exception("4000", ex);
Or a custom exception type with an errorcode property? (This may get confusing with exception types like SqlException which have error codes mapping to SQL Serv开发者_开发问答er errors).
Thanks
Catch the broadest exception that you know how to handle.
In general, this means you'll be catching a pretty specific exception. And some exceptions, like
ArgumentException
s, shouldn't be caught at all b/c they indicate a logic error as opposed to a runtime error. One place where I've found catching a broader exception useful is in the case of File I/O. AnIOException
can be a practical higher-level exception to catch.If you are asked to use error codes, you could get away with using the message property of an exception to wrap it, but I would never use that as a reason to avoid throwing an appropriately typed exception. This is because there are two separate concerns here:
a. The error code is there to provide a specific piece of information that can be looked up in the case of a failure in the field. It should never be used to discriminate between exception types programmatically b/c the language has a specific facility designed for that: exception types.
b. The appropriately typed exception is there to provide a programmatic way of distinguishing between exceptions. The language is designed for it, use it. Don't ever throw a plain
Exception
.I would probably throw an error code into the
Exception.Data
collection. This avoids overwriting messages inException.Message
that would otherwise be very helpful for diagnostic purposes.
This depends on if you want to catch an exact exception or a group of different types of exceptions.
Sometimes you want to add handling for 1 exact exception only. Other times your exception handling will be the same for any type of exception so you can just put catch or just catch Exception
to see what the exception is.
For example you may want to catch only 1 exact exception and no other exception handling. You would do that when you know further up the call stack you are catching the rest of the exceptions but you want to ignore just the one you're catching exactly.
精彩评论