Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
sventevit Avatar asked Jul 18 '11 14:07

sventevit


People also ask

How do I catch all exceptions in Visual Studio?

In the Exception Settings window (Debug > Windows > Exception Settings), expand the node for a category of exceptions, such as Common Language Runtime Exceptions. Then select the check box for a specific exception within that category, such as System.

How do I get out of Debug mode in Visual Studio?

To end a debugging session in Microsoft Visual Studio, from the Debug menu, choose Stop Debugging.

How do I keep debugging in Visual Studio?

In most languages supported by Visual Studio, you can edit your code in the middle of a debugging session and continue debugging. To use this feature, click into your code with your cursor while paused in the debugger, make edits, and press F5, F10, or F11 to continue debugging.


1 Answers

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:

Error 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:

  • 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?
like image 89
Justin Avatar answered Oct 14 '22 17:10

Justin