When I got an unhandled exception into my own application, I always think, what a terrible window is this. If you are thinking the same, this solution is helps to make the unhandled exception is a little bit nicer.
If you would like to catch all of unhandled exceptions, you must sign in the AppDomain.CurrentDomain.UnhandledException event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
private static void OnUnhandledException(Object sender,
UnhandledExceptionEventArgs e)
{
//Implement universal exception handling
}
The best way if you do this on the main entry point of your application on the Program.cs file, before you run your main form.
[MTAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(OnUnhandledException);
Application.Run(new MainForm());
}
On the event handler, first of all you must find the exception. This is on the event argument. After find the exception, you can run another form, which is shows a user friendly picture, or message to the exception.
private static void OnUnhandledException(Object sender,
UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
{
Application.Run(new ExceptionHandler(ex, e.IsTerminating));
}
finally
{
}
}
}
My Exception handler form is a very simple form, I just create an overloadaed constructor, when I get the exception, and write exception message like a text message.
public partial class ExceptionHandler : Form
{
public ExceptionHandler(Exception ex)
{
InitializeComponent();
lblExceptionMessage.Text = ex.Message;
}
public ExceptionHandler()
{
InitializeComponent();
lblExceptionMessage.Text = String.Empty;
}
}
The other thing, what I usually do, when I catch an unhandled exception, I create a little logger, and take a log message to my log file. I implement this solution at the same place, on the OnUnhandledException event handler.
if (ex != null)
{
FileStream fs = new FileStream("MyTrafficError.log", FileMode.Append,
FileAccess.Write, FileShare.None, 1000, false);
StreamWriter sw = new StreamWriter(fs);
try
{
sw.WriteLine("DateStamp: " + DateTime.Now.ToString());
sw.WriteLine("ToString(): " + ex.ToString());
sw.WriteLine("Message: " + ex.Message);
sw.WriteLine("StackTrace: " + ex.StackTrace);
sw.WriteLine("THE END");
sw.Flush();
Application.Run(new ExceptionHandler(ex, e.IsTerminating));
}
finally
{
if (sw != null)
{
fs.Close();
sw.Close();
}
}
This is a good way, to find bugs, when other people tests to your application. When they finished the test, just need to see the log, and you could seen, if something does’nt work perfect.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment