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 Server 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. An IOException
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 in Exception.Message
that would otherwise be very helpful for diagnostic purposes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With