Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Server errors).

Thanks

like image 625
GurdeepS Avatar asked Jun 21 '10 16:06

GurdeepS


1 Answers

  1. 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 ArgumentExceptions, 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.

  2. 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.

like image 62
Greg D Avatar answered Oct 21 '22 02:10

Greg D