捕捉所有异常好还是坏? [英] Catch all exception good or bad?
问题描述
AppDomain.CurrentDomain.UnhandledException + = new UnhandledExceptionEventHandler(myUnexpectedExhandler);
Application.ThreadException + = new System.Threading.ThreadExceptionEventHandler(threadExHandler);
这是一个好或坏的做法。
在项目顶层捕获异常是正确的。在那里,你可以做一些事情,例如登录,将细节回报给你的团队等等。如果可能的话,绝对应该在某个地方发布异常 - 这有助于开发坚实的产品(参见Jeff Atwood的博客文章异常驱动开发作为评论在这个)。
什么是糟糕的做法是捕获异常不适当进一步下来的调用堆栈。唯一的时候你应该抓住一个例外是当你知道如何处理它。当然,你永远不应该永远不要默默地吞下例外。
I've seen in multiple projects a kind of catch all exception to catch all unexpected exception so the app won't crash, i see this usually with :
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(myUnexpectedExhandler);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(threadExHandler);
Is this a good or bad practice.
Catching exceptions at the top level of your project is fine and correct. There, you can do things such as log it, report the details back to your team, etc. Exceptions should definitely be published somewhere if at all possible -- that helps a lot in terms of developing a rock-solid product (see Jeff Atwood's blog post "Exception-Driven Development" for a commentary on this).
What is bad practice is catching exceptions inappropriately further down the call stack. The only time you should catch an exception is when you know exactly what to do with it. Certainly, you should never, ever, ever, ever silently swallow exceptions.
这篇关于捕捉所有异常好还是坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!