I'm trying to capture all unhanded Exceptions in a C# Windows Forms Application. I have added the following code to the Program.cs
file but the exceptions are not captured, I get Exceptions such as NullReferenceException
.
What am I doing wrong?
static void Main()
{
System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandedException);
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
var form = new MainForm();
form.ShowDialog();
}
private static void HandleUnhandledException(Object o)
{
// TODO: Log it!
Exception e = o as Exception;
if (e != null)
{
}
}
private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
HandleUnhandledException(e.ExceptionObject);
}
private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
HandleUnhandledException(e.Exception);
}
EDIT:I'm able to catch the Exceptions when the program is run externally outside Visual Studio,But when debuging from visual studio i cant catch Exception.I know debugging is for error removal.Should i run the program in Build mode to capture Exceptions?