|
|
Title | Catch unhandled exceptions in Visual Basic .NET |
Description | This example shows how to catch unhandled exceptions in Visual Basic .NET. |
Keywords | exceptions, unhandled exceptions, UnhandledException, unhandled errors, unhandled bugs, exceptions, Visual Basic .NET, VB.NET |
Categories | Software Engineering, Tips and Tricks |
|
|
You can add an UnhandledException event handler that intercepts any exceptions that you have not already caught by using Try Catch blocks. This event handler is contained in the file ApplicationEvents.vb, which is normally hidden.
To create this event handler:
- In Solution Explorer, right-click the application and select Properties.
- On the Application tab, click View Application Events. (It's near the bottom so you may need to scroll to find it.)
- In the code editor, open the left dropdown and select "(MyApplication Events)." Then in the right dropdown select UnhandledException.
Now you can catch exceptions that are not caught by other exception handlers.
Note that the exception handler only fires when you are running outside the debugger. In the debugger, the debugger itself catches exceptions that your other code doesn't.
You can set the event handler's e.ExitApplication parameter to True (the default) to make the program exit after the event handler ends or False to let the program try to keep running.
The following code shows the example program's UnhandledException event handler.
|
|
Partial Friend Class MyApplication
' Catch an unhandled exception.
Private Sub MyApplication_UnhandledException(ByVal _
sender As Object, ByVal e As _
Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _
Handles Me.UnhandledException
' If the user clicks No, then exit.
e.ExitApplication = _
MessageBox.Show(e.Exception.Message & _
vbCrLf & "Continue?", "Continue?", _
MessageBoxButtons.YesNo, _
MessageBoxIcon.Question) _
= DialogResult.No
End Sub
End Class
|
|
This code simply displays an error message and sets e.ExitApplication depending on whether you want to continue running.
The program uses the following code to generate an unhandled exception,
|
|
' Generate an unhandled exception.
Private Sub btnCrash_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCrash.Click
Dim i As Integer = 1
i /= 0
End Sub
|
|
Try running the program in and out of the debugger to see the difference.
|
|
|
|
|
|