Never1 catch (Exception ex)
. Period2. There is no way you can handle all the different kinds of errors that you may catch.
Never3 catch an Exception-derived type if you can't handle it or provide additional information (to be used by subsequent exception handlers). Displaying an error message is not the same as handling the error.
从我的角度来看,有几个原因:
- 捕捉和重新抛出的成本很高
- 你最终会丢失堆栈跟踪
- 您的代码中的信噪比较低
如果你知道如何处理specific异常(并将应用程序重置到错误前状态),捕获它。 (这就是为什么它被称为例外 handling.)
要处理未捕获的异常,请侦听适当的事件。在执行 WinForms 时,您需要监听System.AppDomain.CurrentDomain.UnhandledException
,并且 - 如果你这样做Threading
- System.Windows.Forms.Application.ThreadException.
对于网络应用程序,也有类似的机制(System.Web.HttpApplication.Error
).
As for wrapping framework exceptions in your application (non-)specific exceptions (i.e. throw new MyBaseException(ex);
): Utterly pointless, and a bad smell.4
Edit
1 Never is a very harsh word, especially when it comes to engineering, as @Chris pointed out in the comments. I'll admit to being high on principles when I first wrote this answer.
2,3 See 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.