exception anomaly

P

peter z

I have a very simple C# windows app containing two forms. Form1 calls
Form2.ShowDialog() in a try/catch block. Form2 has a button on it that when
pressed throws an exception.

While running in the IDE debugger, the Form1 try/catch works as expected
(ie. the Form1 message box displays the exception message).

When running outside of the IDE (ie. double click on the EXE from Windows
Explorer), the try/catch is not behaving as expected but instead the .Net
runtime unhandled exception dialog pops up.

I'm sure it has to do with the fact that the exception gets thrown from
another form than the try/catch is in (therefore a different WndProc) but
can't figure out why the debugger handles it and the runtime does not. Does
anyone have any explanation for this?

I'd like to use this pattern if possible but not the way it's behaving right
now, that is unacceptable. Any ideas welcome. Even if it's to suggest that
this pattern is inherently wrong :)

-Peter

Here is the relevant code from each form:

Form1:
private void button1_Click(object sender, System.EventArgs e)
{
try
{
Form2 dlg = new Form2();
dlg.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Form2:
private void button1_Click(object sender, System.EventArgs e)
{
Throw();
}

private void Throw()
{
throw new Exception("Form2 exception");
}
 
B

Bruce Wood

Exceptions act differently in WinForms running within the debugger
versus outside the debugger. I saw an excellent technical explanation
here once, but I can no longer find it in the archives.

The basic idea is that when you run your WinForms application undert
the debugger, calls like .ShowDialog() run the way you would expect; as
a direct call, so any exceptions propagate up the stack and return to
your .ShowDialog() call, where you can trap them with a try...catch,
just the way you would expect.

Outside the debugger, a call like ShowDialog() ends up sort of "posting
a request" to the Windows Forms event loop, which then calls your
dialog code the next chance it gets, and show the dialog. So, the
actual caller of your form's ShowDialog() method is the event loop, not
your code where the call appears. Any exceptions are propagated back up
the call stack and into the event loop, where they take your
application down.

You can trap these exceptions using global exception handlers
(ThreadException and ApplicationException, I believe they are), but you
cannot stop them from shutting down your app.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top