Esteban Araya Esteban Araya - 1 year ago 78
C# Question

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:

{ 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.

Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download