为什么只有在运行时的调试在Visual Studio中我的Catch块?我的、Visual、Studio、Catch

由网友(淺歌唱出悲傷)分享简介:code在Program.cs中Code in Program.cs[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);try{A...

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调试器附着 - 通常内置在 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窗体应用程序,那么你应该处理的Application.ThreadException事件。另外,您可以改变与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:

是试图/左右整个C#程序捕获可能吗? Exception在释放模式处理的问题(这个问题是误导命名 - 这是不相关的发布/调试生成设置) C#异常只有在调试的时候抓到? 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?
阅读全文

相关推荐

最新文章