I have an application written in C# / .NET 4 / VS C# Express. During debug session (it didn’t happen with release build, but I can’t say for sure, that it won’t in future) my application exits, without any exception info. The only piece in my code, that closes main form, is accesible only with menu File/Exit and it’s Clicked event handler. So it has to be some … ‘exceptional code’. How can I determine, which piece of code killed my app?
Solution if someone would like to use it:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler( currentDomain_UnhandledException );
Event handler with file logging
void currentDomain_UnhandledException( object sender, UnhandledExceptionEventArgs e ) {
using ( FileStream file = new FileStream( Application.StartupPath + "\\errorlog.txt",
FileMode.Append, FileAccess.Write ) ) {
StreamWriter streamWriter = new StreamWriter( file );
streamWriter.WriteLine( "-------------------------------------------------" );
streamWriter.WriteLine( "---------- " + System.DateTime.Now + " ---------" );
streamWriter.WriteLine( "-------------------------------------------------" );
streamWriter.WriteLine( "Terminating: " + e.IsTerminating );
Exception ex = (Exception)e.ExceptionObject;
while ( ex != null ) {
streamWriter.WriteLine( "--------- Exception: ---------- " );
streamWriter.WriteLine( ex.GetType() );
streamWriter.WriteLine( ex.Message );
streamWriter.WriteLine( ex.HelpLink );
streamWriter.WriteLine( ex.Source );
streamWriter.WriteLine( ex.StackTrace );
ex = ex.InnerException;
}
streamWriter.WriteLine();
streamWriter.Close();
MessageBox.Show( ( (Exception)e.ExceptionObject ).Message );
}
}
First of all, you should have exception handling around all your code.
If it’s still occurring you can attach an event handler to the AppDomain.UnhandledException event
Note that your application is still going to crash, but this at least gives you the ability to log the exception.