从不1 catch (Exception ex)
。第 2期。您无法处理可能捕获的所有不同类型的错误。
如果您无法处理或提供额外信息(供后续异常处理程序使用),切勿3捕获异常派生类型。显示错误消息与处理错误不同。
从我的头顶来看,有几个原因:
- 捕捉和重新投掷是昂贵的
- 你最终会丢失堆栈跟踪
- 您的代码中的信噪比较低
如果您知道如何处理特定异常(并将应用程序重置为错误前状态),请捕获它。(这就是为什么它被称为异常 处理。)
要处理未捕获的异常,请侦听适当的事件。在使用 WinForms 时,您需要倾听System.AppDomain.CurrentDomain.UnhandledException
,并且 - 如果您这样做Threading
-System.Windows.Forms.Application.ThreadException.
对于 Web 应用程序,也有类似的机制 ( System.Web.HttpApplication.Error
)。
至于在您的应用程序(非)特定异常(即throw new MyBaseException(ex);
)中包装框架异常:完全没有意义,而且气味难闻。4
编辑
1 Never是一个非常苛刻的词,尤其是在工程方面,正如@Chris 在评论中指出的那样。当我第一次写这个答案时,我承认我的原则很高。
2,3见1。
4 If you don't bring anything new to the table, I still stand by this. If you have caught Exception ex
as part of a method that you know could fail in any number of ways, I believe that the current method should reflect that in it's signature. And as you know, exceptions is not part of the method signature.