Catch Unhandled Errors

Problem

You want to be notified if your application is about to exit because of an unhandled error, possibly so that you can log the problem or perform some final cleanup.

Solution

Create an event handler for the AppDomain.UnhandledException event.

Discussion

The AppDomain.UnhandledException event fires when an unhandled error occurs, just before the application is terminated. This event doesn’t give you the chance to rectify the problem, but it does provide the exception object, which allows you to log the error and perform last-minute cleanup.

The following Console application uses this technique. Before it exits, it displays information about the offending error.

Public Module ErrorHandlerTest Public Sub Main() ' Connect a default ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.