You can add a Event Handler for event AppDomain.UnhandledException
, this event will be triggered when an exception is not detected/handled.
It allows the application to record information about the exception
before the standard system handler reports the exception for the
user and terminate the application. If enough information about the
state of implementation is available, other measures can be taken
- how to save program data for later recovery.
Caution is advised, because program data may be
corrupted when exceptions are not treated.
Example taken from from here in C#.
Add a line to the main method (by default in the file Program.Cs in a new Windows application):
namespace MyApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
On the line AppDomain.CurrentDomain...
is referencing a function that does not yet exist, so we will create it:
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Erro! Entre em contato com os desenvolvedores com a seguinte"
+ " informação:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
Now your untreated exceptions are being shown in a nice dialog, you can do other things around here - like register the exception, or try to soften the crash hit, you cannot however keep the program running after a crash, there’s no way to take the exception at this point and let the program work.
In VB.NET should look similar to this:
Module MyApp
Sub Main()
Dim currentDomain As AppDomain = AppDomain.CurrentDomain
AddHandler currentDomain.UnhandledException, AddressOf MyHandler
Throw New Exception("Foo")
End Sub
Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
Dim e As Exception = DirectCast(args.ExceptionObject, Exception)
Console.WriteLine("Erro! Entre em contato com os desenvolvedores com a seguinte : " + e.Message)
' Fazer alguma coisa aqui com a exceção não tratada.
End Sub
End MyApp
I forgot to comment that the ultimate goal is not to treat Exception itself, I just want it to be sent to my email. Ultimate goal is to know the bugs that happen in it after I have released its first version.
– Kaizonaro
You decide what to do when an untreated exception is detected, both responses quote this.
– stderr