Reputation: 1
Please look at the following code:
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;
}
}
Why the handler doesn't catch the exception thrown by App constructor?
Upvotes: 0
Views: 1334
Reputation: 169160
Why the handler doesn't catch the exception thrown by
App
constructor?
Simply because there is no dispatcher running before the App
has been constructed.
This is the Main
method that is generated for you by the compiler:
[STAThread]
static void Main(string[] args)
{
App application = new App(); //<-- your throw here
application.InitializeComponent();
application.Run(); //<-- and there is no dispatcher until here
}
From the docs:
When
Run
is called,Application
attaches a newDispatcher
instance to the UI thread. Next, theDispatcher
object'sRun
method is called, which starts a message pump to process windows messages.
You cannot call Run
before the you have actually created the App
object.
Upvotes: 1
Reputation: 174
Instance of App failed to construct, therefore Application.Current doesn't make any sense. You should subscribe on AppDomain.CurrentDomain.UnhandledException
public App() : base()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
throw new InvalidOperationException("exception");
}
private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ExceptionObject.ToString());
}
Upvotes: 0
Reputation: 445
I've worked this way to do the same.
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;
}
}
Upvotes: 0