简体   繁体   中英

Why is my Catch block only running while Debugging in Visual Studio?

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 the Application.SetUnhandledExceptionMode Method .

You are by no means alone in being confused by this:

Because in RELEASE mode at the moment the message box have to be shown yuo're appication is going to be "dead" and you can not stop it by showing MessageBox. In DEBUG mode VS cares about that and breaks on the line that throws an exception.

Regards.

I can't see why this is happening but try rebuilding the solution, if in doubt I always do that. It may or may not fix the problem and you probably have already tried but if you haven't it may fix it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM