Search Amazon:

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 
         Console.WriteLine(EX.StackTrace) 
   End Sub 

   Private Sub MYThreadHandler(ByVal sender As Object, _
     ByVal e As Threading.ThreadExceptionEventArgs) 
      Console.WriteLine(e.Exception.StackTrace) 
   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
Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

If you use this code, please mention "www.TheScarms.com"

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms