为什么我的Catch块只在Visual Studio中调试时运行? [英] Why is my Catch block only running while Debugging in Visual Studio?
问题描述
Program.cs中的代码
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new Form1());
}
catch(Exception ex)
{
MessageBox.Show(Blah ...);
}
}
在Form1中,我有一个代码 throw new Exception();
。
如果我从Visual Studio运行应用程序,那么我的消息框弹出(与消息'Blah ...')。但是,如果我从可执行文件运行应用程序,那么catch块根本就不执行。
为什么有区别?
我正在使用Visual Studio 2010,.NET 4.0,Windows XP。
这是因为标准异常处理Windows窗体应用程序在连接Visual Studio调试器时的行为不同 - 通常, Application.Run
方法中内置的异常处理程序捕获未处理的异常,以便它可以执行以下操作:显示以下对话框:
如果允许将异常抛出 Application.Run
方法之外,那么它将阻止应用程序继续用户按继续(捕获在消息泵外面)。
当调试时,这被禁用,大概是调试器将跳转直接进入未处理异常的调试模式,而不是显示上述对话框。
如果要在Windows窗体应用程序中处理未处理的异常,那么您应该处理 Application.ThreadException
事件。或者,您可以使用 应用程序更改此行为。 SetUnhandledExceptionMode
方法。
您绝对不会因此而迷惑:
- 尝试/抓住整个C#程序可能吗?
- 发布模式下的异常处理问题(这个问题是误导性的 - 这与发布/调试版本设置无关)
- Code in Program.cs
[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Application.Run(new Form1()); } catch (Exception ex) { MessageBox.Show("Blah..."); } }
In Form1 I have a button with the code
throw new Exception("");
.If I run the application from Visual Studio, then my messagebox pops up (with message 'Blah...'). But if I run the application from executable file, then the catch block doesn't execute at all.
Why the difference?
I am using Visual Studio 2010, .NET 4.0, Windows XP.
解决方案This is because the standard exception handling for a Windows Forms application behaves differently when the Visual Studio debugger is attached - normally the exception handler built into the
Application.Run
method catches unhandled exceptions so that it can do things like show the following dialog:If it allowed the exception to be thrown outside of the
Application.Run
method then it would prevent the application from continuing if the user presses "continue" (as the catch is outside of the message pump).When debugging however this is disabled, presumably so that the debugger will jump straight into debugging mode on an unhandled exception rather than the above dialog being shown.
If you wish to handle unhandled exceptions in your Windows Forms application then you should handle the
Application.ThreadException
Event. Alternatively you can alter this behaviour with theApplication.SetUnhandledExceptionMode
Method.You are by no means alone in being confused by this:
- Is try/catch around whole C# program possible?
- Exception handling problem in release mode (this question is misleadingly named - this isn't related to the Release / Debug build setting)
- C# Exceptions only caught when debugging?
这篇关于为什么我的Catch块只在Visual Studio中调试时运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!