Veuillez regarder le code suivant:
public partial class App : Application
{
public App():base()
{
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
throw new InvalidOperationException("exception");
}
private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
e.Handled = true;
}
}
3 Réponses :
J'ai fonctionné de cette façon de faire la même chose.
public partial class App : Application
{
public App():base()
{
Application.Current.DispatcherUnhandledException += new
System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(
AppDispatcherUnhandledException);
throw new InvalidOperationException("exception");
}
void AppDispatcherUnhandledException(object sender,
System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
//do whatever you need to do with the exception
//e.Exception
MessageBox.Show(e.Exception.Message);
e.Handled = true;
}
}
L'instance de l'application n'a pas été construite, donc l'application.current n'a aucun sens. Vous devez vous abonner sur AppDomain.CurrentDomaine.UnhandledException
public App() : base()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
throw new InvalidOperationException("exception");
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ExceptionObject.ToString());
}
Pourquoi le gestionnaire ne comprend pas l'exception projetée par
app code> constructeur? p>Tout simplement parce qu'il n'y a pas de répartiteur exécuté avant que l'application
code> a été construite. p>Il s'agit de la méthode
principale code> générée par le Compilateur: p>xxx pré> à partir du DOCS : P>
Lorsque
exécuter code> est appelé,application code> attache un nouvel dispatcher code> instance code> sur le fil de l'interface utilisateur. Ensuite, la méthode code> code> de l'objet code> est appelée, qui démarre une pompe à message pour traiter les messages Windows. P> blockQquote>Vous ne pouvez pas appeler
exécuter code> avant que vous ayez créé l'objetcode> objet. p> blockQuote>
Stackoverflow.com/a/46804709/591656