agnieszka
agnieszka

Reputation: 15355

Exception refuses to be handled

I tried two ways of catching unexpected unhandled exceptions:

static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += 
                new UnhandledExceptionEventHandler(ErrorHandler.HandleException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                Application.Run(new OCR());
            }
            catch (Exception ex)
            {
                ErrorWindow errorWindow = new ErrorWindow(ex);
                errorWindow.ShowDialog();
                Application.Exit();
            }
        }

When i execute the application using visual studio, everything works fine. if i use exe file in the bin\Debug folder, the exceptions are not handled. Application behaves as if catch block wasn't there. I'm clueless what's going on. any ideas?

edit: exceptio nis not thron in Load

Upvotes: 0

Views: 325

Answers (3)

agnieszka
agnieszka

Reputation: 15355

I should handle System.Windows.Forms.Application.ThreadException - then it works.

Upvotes: 2

Vilx-
Vilx-

Reputation: 107000

I've run into an interesting issue when dealing with J# code.

Assume that the exception being thrown is of type FreakyException. Now, FreakyException inherits from FreakyExceptionBase class, which in turn inherits from Exception class. The trick is that each of them are defined in their own assemblies. Say, FreakyExceptionBase resides in ExceptionBases.dll, but FreakyException itself resides in Worker.dll. Your application only references the Worker.dll, but NOT the ExceptionBases.dll.

In this case your catch(Exception) won't catch FreakyException because .NET will not be able to figure out the inheritance chain that specifies that FreakyException actually inherits form Exception.

This happened with J# code because J# exceptions inherit from java.lang.exception, and my project wasn't referencing J# libraries. When J# was referenced, the problem went away.

Perhaps it is the same case with your application?

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063884

I take it that you have an exception in your Form's OnLoad method or Load event, then. This is a notorious issue, which isn't helped by the IDE making it behave differently. Basically, you need to make sure that your OnLoad/Load don't throw... perhaps put the catch in there, and set a property you can check afterwards?

Upvotes: 4

Related Questions