Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why win32 exception are not caught by c# exception handling mechanism

I have a winforms application.Winforms start with Program.cs where we have main() defined.I have put this code in try-catch block.

 [STAThread]
    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmSplash());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            if (ex.InnerException != null)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
        }
    }

Whenever there is a win32 exception,this mechanism fails and unhandled exception message is thrown and application crashes.
I have 2 questions regarding this code:

1) Why win32 exceptions are not caught.

2) Is it a good practice to catch exceptions at the highest level.

like image 446
Rohit Raghuvansi Avatar asked Jul 30 '09 09:07

Rohit Raghuvansi


2 Answers

EDIT : as Pratik pointed out, the following answer applies to .NET 1.0 and .NET 1.1 only. Starting with .NET 2.0, non-CLS exception should be caught as a RuntimeWrappedException.


Because Win32 exceptions do not derive from the .NET Exception class. Try :

try {
} catch (Exception ex) {
    // .NET exception
} catch {
    // native exception
}

See Catch non-CLSCompliant exceptions in general handlers for more information.

like image 175
Mac Avatar answered Oct 19 '22 12:10

Mac


The execution of Application.Run is not throwing an error. That is happening on another thread (or at least asynchronously).

Its good idea to inform the user in friendly way that the application has failed before it disapears completely, however its not a good idea to just catch then continue.

like image 36
AnthonyWJones Avatar answered Oct 19 '22 11:10

AnthonyWJones