J'utilise l'événement Application.ThreadException pour gérer et enregistrer les exceptions inattendues dans mon application WinForms.Très étrange comportement Application.ThreadException
Maintenant, quelque part dans ma demande, j'ai le code suivant (ou plutôt quelque chose d'équivalent, mais ce code fictif est suffisant pour reproduire mon problème):
try
{
throw new NullReferenceException("test");
}
catch (Exception ex)
{
throw new Exception("test2", ex);
}
Je me attends clairement mon Application_ThreadException handler à passer l'exception "test2", mais ce n'est pas toujours le cas. En règle générale, si un autre thread amène mon code à l'interface utilisateur, mon gestionnaire reçoit l'exception «test», exactement comme si je n'avais pas du tout attrapé «test».
Voici un court exemple reproduisant ce comportement. J'ai omis le code du concepteur.
static class Program
{
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // has no impact in this scenario, can be commented.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//this handler is never called
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click+=new EventHandler(button1_Click);
}
protected override void OnLoad(EventArgs e) {
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThrowEx));
t.Start();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
throw new NullReferenceException("test");
}
catch (Exception ex)
{
throw new Exception("test2", ex);
}
}
void ThrowEx()
{
this.BeginInvoke(new EventHandler(button1_Click));
}
}
La sortie de ce programme sur mon ordinateur est:
test
... here I click button1
test2
J'ai reproduit ce sur .net 2.0,3.5 et 4.0. Est-ce que quelqu'un a une explication logique?
Réponse modifiée. –
Votre suggestion a un sens, mais cela ne change pas le comportement étrange. – Brann
@Brann, vous avez raison.Le comportement étrange persiste. Cependant, je l'ai corrigé en ne faisant pas 'catch (Exception ex)' dans le gestionnaire de clic de bouton, mais plutôt juste 'catch'. Très intéressant. Une exception non decendand d'Exception étant levée. –