简体   繁体   中英

How do you suppress errors to a method call in C#?

I'm looking for an "elegant" way to suppress exceptions when calling a method.

I think the following code is way too verbose:

try
{ CallToMethodThatMayFail(3); }
catch {}

Is there some syntactic sugar I can use to say "I don't really care if this method fails"? I want to call the method and continue execution regardless of what happens with the method.

It is rarely a good idea to ignore/swallow errors...

To allow re-use, the only option you have is something like a method that takes an Action :

 static void IgnoreErrors(Action action) {try {action();} catch {}}

But you haven't exactly saved much by the time you've done:

SomeHelper.IgnoreErrors(() => CallToMethodThatMayFail(3));

I'd just leave the try / catch in place...


Re the question in the comment:

static void IgnoreErrors<T>(Action action) where T : Exception
{
    try { action(); } catch (T) {}
}

SomeHelper.IgnoreErrors<ParseException>(() => CallToMethodThatMayFail(3));

but I would still find it clearer to have the try / catch locally...

Nope this is it.

And it's a good thing it's verbose. If you're suppressing a possible exception you better have a very good reason. The verbosity will help you or the next person who looks at the code in a few months.

Using Castle, you could do something like this:

public class ExceptionSuppressionInterceptor : Castle.Core.Interceptor.IInterceptor
{
   public void Intercept(IInvocation invocation)
   {
       try {
           invocation.Proceed();
       }
       catch (Exception ex) {
            // Suppressed!
       }
   }
}

And decorate the class you want to suppress exceptions for like this:

[Interceptor(typeof(ExceptionSuppressionInterceptor))]
public class GoodPracticeBreaker {

}

But you really probably shouldn't.

I don't know of anything more terse. I suppose you could do some AOP or similar for something more fancy.

.Net约定是类实现TryCallMayFail()方法和CallMayFail()方法,调用者选择使用哪一个,但TryCallMayFail()方法将包含你在那里的确切内容。

No, there's no better way to do this, and there's a good reason for it. The exception you see may mean more than "the method failed". It may mean, "the system is failing".

You probably should at least log the fact of the failure, in case it turned out to be important after all.

Why do you say this is too verbose? If you are trying to save keystrokes, you can just use a code snippet. If you are concerned about readability, then I think that an AOP method would be less clear to another maintainer (at least initially) and for me, this outweighs the verbosity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM