User Tools

Site Tools


development:net:catch_all

Catch and handle all unhandeled exceptions

.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.

Public Class Form1
Dim currentDomain As AppDomain = AppDomain.CurrentDomain

Private Sub MYExnHandler(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
Dim EX As Exception
EX = e.ExceptionObject
MsgBox(EX.Message, MsgBoxStyle.Critical, EX.GetType.ToString)
End Sub

Private Sub MYThreadHandler(ByVal sender As Object, ByVal e As Threading.ThreadExceptionEventArgs)
MsgBox(e.Exception.Message, MsgBoxStyle.Critical, e.Exception.GetType.ToString)
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
AddHandler currentDomain.UnhandledException, AddressOf MYExnHandler ' Define a handler for unhandled exceptions.
AddHandler Application.ThreadException, AddressOf MYThreadHandler ' Define a handler for unhandled exceptions for threads behind forms.
End Sub

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
' This code will throw an exception and will be caught by the handlers.
Dim N As Integer = 1
N = N / 0
End Sub
End Class
development/net/catch_all.txt · Last modified: 2017/11/23 10:48 by tplecko