Ignore Exception in C#

后端 未结 9 733
梦毁少年i
梦毁少年i 2020-11-29 11:15

Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a codeblock,

相关标签:
9条回答
  • 2020-11-29 11:42

    Empty catch blocks are a very stinky code smell. In short, you should not be pursuing a shorthand way of writing them.

    Rule #1 is, "don't catch it if you can't handle it." Rule #1a is, "if you didn't actually handle the Exception, re-throw it."

    If you're just trying to prevent the app from crashing, there are more appropriate mechanisms to use in most circumstances. .NET includes UnhandledException events at the Application, Dispatcher, and AppDomain levels, as well as events dedicated to notifying you of unhandled exceptions on background threads. At this level, if you cannot verify the state of your app, your best option may well be to notify the user something bad has happened and terminate the app.

    0 讨论(0)
  • 2020-11-29 11:47

    I don't know any mechanism that would allow you to do this.

    Generally, it is also considered a very bad practice to ignore exceptions. Exceptions are (or should always be) raised for a good reason; if nothing else, you should at least log them.

    If you know that a certain type of exception is not critical to your application, you can prevent it from crashing using the Application.UnhandledException event, checking for that kind of exception. Note that this will still propagate the exception through all stack frames to the very bottom.

    0 讨论(0)
  • 2020-11-29 11:49

    You can do it with AOP. Postsharp for example will allow you to easily implement such an attribute which will skip particular exceptions in methods to which you applied such an attribute. Without AOP I do not see any good way to do that (if we assume that there is a good way to do such things ;) ).

    With Postsharp you will be able to decorate your methods in this way:

    [IgnoreExceptions(typeof(NullReferenceException), typeof(StackOverflowException))]
    void MyMethod() { ... }
    
    0 讨论(0)
提交回复
热议问题