捕捉所有异常好还是坏? [英] Catch all exception good or bad?

查看:180
本文介绍了捕捉所有异常好还是坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多个项目中看到一种捕获所有异常的异常,以捕获所有意外的异常,所以应用程序不会崩溃,我通常看到:

  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屋!

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