Catch and handle all unhandled exceptions in a VB.NET program

.NET allows you to catch and handle any unhandled exception that occurs in your program. By an unhandled exception I mean one that is not caught by a Try-Catch statement. Good error handling is critical and the best bet is to use Try-Catch-Finally blocks.

However, using the current Application Domain you can catch any error that occurs outside of a Try-Catch block. An application domain is an isolated environment where an application executes. Application domains provide isolation, unloading, and security boundaries for executing managed code. Basically, they prevent one application from interferring with another. Applications Domains are represented by the AppDomain object.

To catch unhandled errors, you need to get the current application domain, set up two event handler routines and add two event handler definitions.

VB.NET code to catch and handle unhandled exceptions:

   ' Get the your application's application domain.
   Dim currentDomain As AppDomain = AppDomain.CurrentDomain 

   ' Define a handler for unhandled exceptions.
   AddHandler currentDomain.UnhandledException, AddressOf MYExHandler 

   ' Define a handler for unhandled exceptions for threads behind forms.
   AddHandler Application.ThreadException, AddressOf MYThreadHandler 

   Private Sub MYExnHandler(ByVal sender As Object, _
       ByVal e As UnhandledExceptionEventArgs) 
         Dim EX As Exception 
         EX = e.ExceptionObject 
   End Sub 

   Private Sub MYThreadHandler(ByVal sender As Object, _
     ByVal e As Threading.ThreadExceptionEventArgs) 
   End Sub

   ' This code will throw an exception and will be caught.
   Dim X as Integer = 5
   X = X / 0 'throws exception will be caught by subs below

About TheScarms
About TheScarms

Sample code
version info

If you use this code, please mention ""

Email this page

© Copyright 2024 TheScarms
Goto top of page