Reputation: 1798
I'm using the following code to display unhandled exceptions in a WPF application:
public MyApplication() {
this.DispatcherUnhandledException += (o, e) => {
var exceptionMessage = new ExceptionWindow();
exceptionMessage.ExceptionMessage.Text = e.Exception.Message;
exceptionMessage.ExceptionCallStack.Text = e.Exception.StackTrace;
exceptionMessage.ExceptionInnerException.Text = e.Exception.InnerException.Message;
exceptionMessage.WindowStartupLocation = WindowStartupLocation.CenterScreen;
exceptionMessage.WindowStyle = WindowStyle.ToolWindow;
exceptionMessage.ShowDialog();
e.Handled = true;
Shell.Close();
};
}
Turns out that I have an exception during the instantiation of the application, so the app constructor is never executed.
A simple way to reproduce it (with a different exception) is by introducing an extra "<" before some tag in your app's configuration file and run it.
A useless error message like that appears before the application constructor get called. alt text http://srtsolutions.com/cfs-filesystemfile.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/mikewoelmer/ExceptionWPF1_5F00_1C1F39AA.jpg
Does anyone know how to catch such kind of exceptions?
Remark: I'm using Caliburn and my application extends CaliburnApplication.
Upvotes: 2
Views: 1167
Reputation: 1798
Okay. I solved the problem by doing the following:
Change the Build Action
of the App.xaml
file from ApplicationDefinition
to Page
.
Create a new class like following:
public class AppStartup {
[STAThread]
static public void Main(string[] args) {
try {
App app = new App();
app.InitializeComponent();
app.Run();
}
catch (Exception e) {
MessageBox.Show(e.Message + "\r\r" + e.StackTrace, "Application Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
It replaces the generated App.g.cs Main method by this one, so we have a chance to catch the exceptions.
Upvotes: 5