为什么只有在运行时的调试在Visual Studio中我的Catch块? [英] Why is my Catch block only running while Debugging in Visual Studio?

查看:159
本文介绍了为什么只有在运行时的调试在Visual Studio中我的Catch块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code在Program.cs中

Code in Program.cs

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    try
    {
        Application.Run(new Form1());
    }
    catch (Exception ex)
    {
        MessageBox.Show("Blah...");
    }
}

在Form1中我与code 抛出新的异常()按钮;

In Form1 I have a button with the code throw new Exception("");.

如果我运行从Visual Studio中的应用程序,然后我的消息框弹出(与消息等等...)。但是,如果我运行的可执行文件的应用程序,那么catch块不执行的。

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.

为什么不同?

我在使用Visual Studio 2010,.NET 4.0,Windows XP中。

I am using Visual Studio 2010, .NET 4.0, Windows XP.

推荐答案

这是因为标准异常处理Windows窗体应用程序的行为不同,当Visual Studio调试器附着 - 通常内置在<$ C $异常处理程序C> Application.Run 方法捕获未处理的异常,以便它可以做的事情一样显示下面的对话框:

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:

如果它允许例外,在 Application.Run 方法之外抛出那就prevent应用持续,如果用户presses继续(如抓的消息泵外)。

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).

在调试然而,这被禁用,正在显示presumably使调试器会直接跳到调试模式未处理的异常,而不是上面的对话框。

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.

如果你想处理未处理的异常在你的Windows窗体应用程序,那么你应该处理的<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx"><$c$c>Application.ThreadException事件。另外,您可以改变与<一本行为href="http://msdn.microsoft.com/en-us/library/ms157905.aspx#Y600"><$c$c>Application.SetUnhandledExceptionMode方法。

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 the Application.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?

这篇关于为什么只有在运行时的调试在Visual Studio中我的Catch块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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