You can add an event handler to AppDomain.UnhandledException
, this event will fire when an exception is not detected / handled.
It allows the application to log information about the exception
before the system's default handler reports the exception to the
and quit the application. If sufficient information
state of the application is available, other measures can be taken
- how to save program data for later recovery.
Caution is advised because the program data can be
corrupted when exceptions are not handled.
Example taken from here in C #.
Add a line to the main method (by default in the Program.cs file 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());
}
}
}
At line AppDomain.CurrentDomain...
you are 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 unhandled exceptions are being displayed in a nice dialog, you can do other things around here - such as logging the exception, or trying to smooth out the crash, you can not, however, keep the program running after a < in> crash , there is no way to catch 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