忽略C#中的exception

有没有更好的方法来忽略C#中的exception,而不是将它放在try catch块中并且在catch中什么都不做? 我发现这种语法很麻烦。 对于代码块,我不能简单地以这种方式“标记”它,以便运行时知道忽略哪些exception?

我不认为有一个技巧可以避免exception,但您可以使用以下代码片段:

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

使用该方法如下:

 IgnoreExceptions(() => foo()); 

另一个解决方案是使用AOP(面向方面​​编程) – 有一个名为PostSharp的工具,它允许您创建一个属性,该属性将捕获特定程序集/类/方法中的所有exception,这更接近您正在寻找的内容。

你可以用AOP做到这一点。 例如,Postsharp将允许您轻松实现这样的属性,该属性将跳过应用此类属性的方法中的特定exception。 没有AOP我没有看到任何好的方法(如果我们假设有一个很好的方法来做这些事情;))。

使用Postsharp,您将能够以这种方式装饰您的方法:

 [IgnoreExceptions(typeof(NullReferenceException), typeof(StackOverflowException))] void MyMethod() { ... } 

一种方法是利用面向方面编程(AOP)。 看看PostSharp 。 下面是一个在方法上使用exception属性的示例,这样如果发生exception,您可以在try..catch块中处理它。

编辑:

啊,是的,Dror的建议也很好。 我在企业库中看到过这样的例子。 如果您不希望项目中有第三方框架(即PostSharp),那会更好。

我不知道任何允许你这样做的机制。

通常,忽略exception也被认为是一种非常糟糕的做法。 有充分理由提出(或应该总是)例外情况; 如果没有别的,你至少应该记录它们。

如果您知道某种类型的exception对您的应用程序并不重要,您可以使用Application.UnhandledException事件阻止它崩溃,检查那种exception。 请注意,这仍然会将exception通过所有堆栈帧传播到最底层。

不会。当出现exception时,它们会向上移回调用堆栈,直到它们被catch块处理或整个过程终止。

我想根据之前的答案贡献我创建的扩展方法。 希望它可以帮到某人。

 ///  /// Extension methods for  objects. ///  public static class ActionExtensions { ///  /// Executes the  and ignores any exceptions. ///  ///  /// This should be used in very rare cases. ///  /// The action to execute. public static void IgnoreExceptions(this Action action) { try { action(); } catch { } } ///  /// Extends an existing  so that it will ignore exceptions when executed. ///  /// The action to extend. /// A new Action that will ignore exceptions when executed. public static Action AddIgnoreExceptions(this Action action) { return () => action.IgnoreExceptions(); } } 

unit testing:

 [TestClass] public class ActionExtensionsTests { [TestMethod] public void IgnoreException() { Action justThrow = () => { throw new InvalidOperationException(); }; justThrow.IgnoreExceptions(); } [TestMethod] public void AddIgnoreException() { Action justThrow = () => { throw new InvalidOperationException(); }; var newAction = justThrow.AddIgnoreExceptions(); newAction(); } } 

不会。如果抛出exception,通常会发生严重错误。 你不想忽视它。

相反,您应该重写代码以检查错误,并且只有在它确实失败时才会抛出exception。

例如,使用Int32.TryParse而不是Int32.Parse来检查对象是否是有效整数。 请记住,exception是非常昂贵的,并且许多演员表会严重影响应用程序的性能。

空捕获块是一种非常臭的代码味道。 简而言之,你不应该采用简写的方式来编写它们。

规则#1是,“如果你不能处理它,就不要抓住它。” 规则#1a是,“如果你没有真正处理exception,重新抛出它。”

如果您只是想阻止应用程序崩溃,那么在大多数情况下可以使用更合适的机制。 .NET包括Application,Dispatcher和AppDomain级别的UnhandledException事件,以及专门用于通知您后台线程上未处理的exception的事件。 在此级别,如果您无法validation应用程序的状态,最好的选择可能是通知用户发生了不好的事情并终止应用程序。

  public static void Ignore(Action a) where T : Exception { try { a(); } catch (T) { } } 

使用:

  Ignore(() => foo());