I am assuming you want to catch and do something with all unhandled exceptions within your code. I will leave it to you to put the proper using statements at the top of your files.
Do something like this:
In your main within program.cs near the beginning of the function:
Application.ThreadException += new ThreadExceptionHandler(UnhandledExceptionEventHandler);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Then, write your handlers like this:
public void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
ExceptionHandler((Exception)e.ExceptionObject);
}
public void UnhandledExceptionEventHandler(object sender, ThreadExceptionEventArgs e)
{
ExceptionHandler(e.Exception);
}
public void ExceptionHandler(Exception e)
{
string result = FormatException(e, string.Format("Information: {0}\n\n", Assembly.GetEntryAssembly().GetName()));
}
public string FormatException(Exception e, params string[] information)
{
Exception ex = e;
StringBuilder sb = new StringBuilder();
if (information != null)
{
foreach (string s in information)
sb.Append(s);
}
while (ex != null)
{
sb.AppendLine(ex.GetType().ToString());
sb.AppendLine(ex.Message);
sb.AppendFormat("\n\nStack Trace:\n{0}", ex.StackTrace);
ex = ex.InnerException;
if (ex != null)
sb.AppendFormat("\n\nInner Exception:\n\n");
}
return sb.ToString();
}