为什么的try-catch在main()不好? [英] Why are try-catch in main() bad?

查看:221
本文介绍了为什么的try-catch在main()不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么它被认为inapropriate有一个try-catch在main()方法来捕捉任何未处理的异常给我有人能解释一下吗?

Could someone explain to me why it is considered inapropriate to have a try-catch in the main() method to catch any unhandled exceptions?

[STAThread]
static void Main()
{
    try
    {
        Application.Run(new Form1());
    }
    catch (Exception e)
    {
         MessageBox.Show("General error: " + e.ToString());
    }
}



我的理解,这是不好的做法,但不知道为什么。

I have the understanding that this is bad practice, but not sure why.

推荐答案

我不认为它的不一定的坏习惯。有几个注意事项但是...

I don't think its necessarily bad practice. There are a few caveats however...

我相信任何人称之为坏习惯的点是加强你应该抓住的想法异常的最接近他们发生的(即高调用堆栈尽可能/ appropiate)。制毯异常处理程序通常不是一个好主意,因为它大大减少可使用的控制流。粗粒度的异常处理是很重要的的合理解决方案的稳定性。不幸的是,许多初学者开发者认为这是,采取这种办法,因为这毯try-catch语句。

I believe the point of whoever called this "bad practice" was to reinforce the idea that you should be catching exceptions closest to where they occur (i.e. as high up the call stack as possible/appropiate). A blanket exception handler isn't typically a good idea because its drastically reduces the control flow available to you. Coarse-grained exception handling is quite importantly not a reasonable solution to program stability. Unfortunately, many beginner developers think that it is, and take such approaches as this blanket try-catch statement.

说着,如果的你的利用异常在程序的其余部分处理妥善,(在一个特定的任务细粒度和方式),以及处理错误相应那里(而不是尤斯特显示一个通用的错误框)的然后的一般的try-catch在主营例外方法可能是有一个有用的东西。有一点这里要注意的是,如果你的 reproducably 的抓住了这个漏洞获得的try-catch,那么你要么有一个bug或东西是不对您的本地化的异常处理。

Saying this, if you have utilised exception handling properly (in a fine-grained and task-specific manner) in the rest of your program, and handled the errors accordingly there (rather than juist displaying a generic error box), then a general try-catch for all exceptions in the Main method is probably a useful thing to have. One point to note here is that if you're reproducably getting bugs caught in this Main try-catch, then you either have a bug or something is wrong with your localised exception handling.

这的try-catch与主要的主要用途将是纯粹防止程序在特殊情况下崩溃,而且应该做并不比显示(隐约)人性化的致命错误的消息给用户更多的,以及可能的地方记录错误和/或提交错误报告。于是得出结论:这种方法的确实的有用武之地,但必须非常谨慎地进行,而不是出于错误的理由。

The primary usage of this try-catch with Main would be purely to prevent your program from crashing in very unusual circumstances, and should do hardly any more than display a (vaguely) user-friendly "fatal error" message to the user, as well as possibly logging the error somewhere and/or submitting a bug report. So to conclude: this method does have its uses, but it must be done with great care, and not for the wrong reasons.

这篇关于为什么的try-catch在main()不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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