Ignore Exception in C#

后端 未结 9 747
梦毁少年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条回答
  •  Happy的楠姐
    2020-11-29 11:31

    I don't think there is a trick to avoid exception but you can use the following code snippet:

    public void IgnoreExceptions(Action act)
    {
       try
       {
          act.Invoke();
       }
       catch { }
    }
    

    Using the method looks like:

    IgnoreExceptions(() => foo());
    

    Another solution is to use AOP (Aspect Oriented Programming) - there's a tool called PostSharp which enables you to create an attribute that would catch all exceptions in specific assembly/class/method, which is closer to what you're looking for.

提交回复
热议问题