开发者

Exceptions not caught in release build (WinForm desktop app, C#, VS 2010)

开发者 https://www.devze.com 2023-01-19 04:28 出处:网络
I developed a desktop application, it\'s almost done but still contains some bugs which I\'m eliminating.

I developed a desktop application, it's almost done but still contains some bugs which I'm eliminating.

I use a general [try...catch] block wrapped around my application

[STAThread]
static void Main()
{
   try
   {
       program = new Program();
       // ...
   }
   catch (Exception x)
   { 
       // ...
       MessageBox.Show(
          message,
          Resources.MESSAGEBOX_ERROR_CRASH_Caption,
          MessageBoxButtons.OK,
          MessageBoxIcon.Error);
   } 
}

my Program class constructor being:

public Program()
{
    // [...]
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    // [...]
    frmLogon = new Logon();            
    Application.Run(frmLogon);
}        

to ensure that any unhandled exception will bubble all the way up the stack and is at least responded to with some communicative message box.

It works fine when I run the application under Visual Studio (debug mode), but when I deployed it and installed on my PC, it doesn't - that's what I get when the bug (which I've already identified, by the way) causes it to read from a null array

Exceptions not caught in release build (WinForm desktop app, C#, VS 2010)

Why? It baff开发者_JAVA技巧les me really. Why was it "unhandled"? It was my understanding that try...catch should work regardless of whether it's release or debug mode, otherwise what would be the point.


This is kind of old, but if you still need a solution, you need to handle some events, enclosing the entire thing in a try catch won't work. Do something like this:

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        AppDomain.CurrentDomain.UnhandledException += ProcessAppException;
        Application.ThreadException += ProcessThrException;
        Application.Run(new MainForm());
    }

    private static void ProcessAppException(object sender, UnhandledExceptionEventArgs e)
    {
        XtraFunctions.LogException((Exception)e.ExceptionObject);
        throw (Exception)e.ExceptionObject; //MessageBox in your case.
    }

    private static void ProcessThrException(object sender, ThreadExceptionEventArgs e)
    {
        XtraFunctions.LogException(e.Exception);
        throw e.Exception; //MessageBox in your case.
    }

When an exception isn't caught, it will go through one of those before displaying the exception dialog. So you have the option to override it and display a nice message of your choice.

0

精彩评论

暂无评论...
验证码 换一张
取 消