Hi,
This is my Program class in my Application -
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Subscribe to thread (unhandled) exception events
ThreadExceptionHandler handler = new
ThreadExceptionHandler();
Application.ThreadException += new
ThreadExceptionEventHandler(handler.ApplicationThreadException);
Application.Run(new FormMain());
}
/// <summary>
/// Handles any thread exceptions
/// </summary>
public class ThreadExceptionHandler
{
// set when there is an unhandled exception. Can therefore
be used by FormMain.
static bool unhandeledException = false;
public static bool UnhandeledException { get { return
unhandeledException; } }
public void ApplicationThreadException(object sender,
ThreadExceptionEventArgs e)
{
try
{
unhandeledException = true;
ShowThreadExceptionDialog(e.Exception);
}
finally
{
// Fatal error, terminate program
Application.Exit();
}
}
/// <summary>
/// Creates and displays the error message.
/// </summary>
private void ShowThreadExceptionDialog(Exception ex)
{
from with FormMain I do the following if there is an exception which
is to not save the users settings -
private void OnClosing(object sender, EventArgs ev)
{
if (Program.ThreadExceptionHandler.UnhandeledException)
return;
// save user settings...
}
The problem though is that if I create a thread as follows, exceptions
are not being handled by ThreadExceptionHandler -
public void FormMain_Load(object sender, EventArgs e)
{
thread = new System.Threading.Thread(MyThread);
thread.Start();
}
void MyThread()
{
throw new ApplicationException("My exception");
}
Why not?
Thanks as ever,
Aine
Peter Duniho - 13 Nov 2007 18:15 GMT
> [...]
> The problem though is that if I create a thread as follows, exceptions
> are not being handled by ThreadExceptionHandler -
>
> [...]
> Why not?
Just to be clear: the Application.ThreadException event doesn't offer a
way to _handle_ an exception. You'll be notified of the exception, but
handling implies that you've successfully caught it and the thread can
proceed normally.
As for why your event handler isn't being called, I don't really know.
Have you called Application.SetUnhandledExceptionMode to enable the
event? I'm not sure what the configuration file default is, but it
could be that it's simply set currently to not raise the
ThreadException event.
Pete