开发者

Best C# syntax for ignoring an exception

There are some 开发者_高级运维cases we don't care about the Exception and just need to resume. I know it's side-effects and ...

Here my question is about the best C# syntax for ignoring an exception, for example:

try
{
   // exceptional code
}
catch { }

but this seems a little ugly specially that empty brackets after catch. Is there a more elegant syntax ?


You should never have an empty catch statement like that. Having an error in the code and not even noticing it is worse than just having an error in the code.

If you really want to catch exceptions and ignore them, try to catch only the type of exception that you want to ignore, and add a comment about the reason for ignoring it:

try {
  // exceptional code...
} catch(FormatException) {
  // A comment describing why on earth you are cathing
  // an exception and ignoring it.
}


Ummm.. I don't think there is anything "inelegant" about the two braces (the fact that you're swallowing exceptions with not so much as a comment is however). You must have better problems to worry about.


Probably not the best route, but you could do this to be a little more descriptive:

try
{
    //  exceptional code
}
catch (Exception ex)
{
}

However, I think the empty brackets convey the same message to whoever is maintaining this in the future.

Better still would be to refactor your exceptional code. If you're ignoring an exception, chances are it could (and should) be done a better way.


I think convention would be that typically when ignoring exceptions, you are ignoring exceptions of a specific type and at least providing some handling for System.Exception. Either way, I would document in the catch why the corresponding exception is being ignored.

try {

   ... exceptional code

} catch (InvalidOperationException ex) {
   // This exception can be ignored because ..
} catch (Exception ex) {
   ... error handling code
}


You can use Spring.NET AOP

Exception Handler Advice

Excerpts from the link

The source exceptions to perform processing on are listed immediately after the keyword 'on' and can be comma delmited. Following that is the action to perform, either log, translate, wrap, replace, return, or swallow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜