您如何抑制C#中的方法调用错误? [英] How do you suppress errors to a method call in C#?

查看:89
本文介绍了您如何抑制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.

推荐答案

忽略它很少是一个好主意/ swallow错误...

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

要允许重复使用,您唯一的选择是类似采取 Action

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

在评论:

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

这篇关于您如何抑制C#中的方法调用错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆