C# 2.0 Exception Handling - Can't Understand MSDN Example

O

orekinbck

Hi There

I'm probably missing something fundamental here but I don't understand
the code in the OnThreadException routine, which is found in MSDN under
the topic: Application.ThreadException Event

I think the whole OnThreadException routine could be replaced with two
lines of code:

if (ShowThreadExceptionDialog(t.Exception) == DialogResult.Abort)
Environment.Exit(0);

Why? Because:
(1) FXCop complains about the MSDN example with CA1031 :
Microsoft.Design : Modify ... to catch a more specific exception than
'System.Object' or rethrow the exception.
(2) I don't understand why they even bother catching an exception as
they just give a totally useless message and terminate the application
anyways:

try
{
MessageBox.Show("Fatal Error", "Fatal Error" ...
}
finally
{
Application.Exit();
}

(3) Environment.Exit is more relevant for the project I am working on
as Application.Exit(0) only seems to end the blocking
Application.Run(new myMainForm()) line. If there is code after the
Application.Run line it will still be executed. However I want to give
the application a "bullet in the head".

Thanks In Advance
Bill
 
O

orekinbck

Actually, I just realized a design flaw in the sample code:

try
{
result = this.ShowThreadExceptionDialog(t.Exception);
}
catch
{
try
{
MessageBox.Show("Fatal Error", "Fatal Error",
MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}

In the second try clause, why give the user the option to Abort / Retry
/ Ignore if the finally clause is just going to Application.Exit()
anyway ?
 
N

Nicholas Paldino [.NET/C# MVP]

Bill,

Regarding giving your app a "bullet in the head", you would have to call
the static Exit method on the Environment class. However, I wouldn't
recommend this.

When you call Application.Exit, you are sending a WM_QUIT message to the
message loop, which then terminates the loop, and the code after your loop
executes.

What you should do is set a flag that can be read after the loop
executes, and then call Application.Exit (setting the flag before you make
the call). When the call to Application.Run completes (this is your message
loop), check the flag. If it is true, then just return.

Hope this helps.
 

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