Reputation: 53243
Is it possible to formulate to have a guide-line to answer:
In what cases a developer should not handle a particular exception?
To express myself better, if a method is expecting one of the values of 1,2,3,4,5 for parameter: "Zeta" and from the business logic point of view if it is meaningless that 9 cannot be pased as a parameter value, should the developer still handle of a possible argument exception?
Upvotes: 3
Views: 125
Reputation: 124696
I'll be somewhat contrarian here, as just about every recommendation I've ever seen will suggest (sometimes vehemently) that you should only check for specific exceptions you expect (a "white list" of exceptions you can handle).
However given the lack of a concept of checked exceptions in .NET, in many cases you can never be sure what exceptions will be thrown, especially in loosely-coupled applications. For example, assuming I have injected an encryption implementation using IoC, who can give me an exhaustive list of all possible exceptions that could be thrown by current and future versions of the .NET cryptography classes?
In such cases, it is reasonable to have a "black list" of exceptions you don't want to handle, which you can do something like:
try
{
...
}
catch(Exception ex)
{
if (IsInBlackList(ex))
{
throw;
}
... code to recover from exception ...
}
There are precedents for this in the .NET Framework itself, for example, the System.Windows.Forms.Application.CommonAppDataPath
does exactly this, using an internal method ClientUtils.IsSecurityOrCriticalException
to define its "black list".
Upvotes: 0
Reputation: 29468
In general, one should avoid exceptions. So for example instead of letting a NullReferenceException happen, check for null
instead. Always check all your arguments for validy and throw an ArgumentException
if you find invalid values.
Never catch System.Exception
, but instead alway just the specific Exceptions you expect. Otherwise you can hide serious bugs and probolems in your software.
Upvotes: 0
Reputation: 7964
You should avoid catching all non-software exceptions/errors. For example OutOfMemory error is one such exception. Catching the exception is generally used for preventing your application to crash/exit. And this should be done only and only when the exception is related to some wrong input to application or some programmatic bug.
Upvotes: 0
Reputation: 39898
if you look at the Exceptions documentation from MSDN it states the following:
So the developers should only catch the exceptions they can handle. If for example a user typed the number 9 which is considered an error, a message could be displayed to the user and ask for new input.
If the developer can't handle the ArgumentException when 9 is passed he shouldn't catch it.
Upvotes: 3