Jump to content

Visual Basic .NET/Exception handling

From Wikibooks, open books for an open world

Exception handling

[edit | edit source]

There are two main ways to handle errors in code, in order to avoid to stop the program when they occur.

On Error GoTo

[edit | edit source]

The older method used in VBA is "unstructured" error handling, still available via the On Error GoTo syntax, because it uses a Goto toward a label. This is still useful in certain circumstances where you wish to Resume processing after handling the error.

    Public Sub Main()
        On Error GoTo Label1
        Dim Result As Integer = 1
        Dim a = 1
        Dim b = 0
        Result = a / b  ' Division by zero
Label1:
        MessageBox.Show(Result)
    End Sub

To avoid to define the labels, it's possible to simply ask to ignore all errors, during a certain time, and reactivate them with On Error GoTo 0:

        On Error Resume Next
        Dim Result As Integer = 1
        Dim a = 1
        Dim b = 0
        Result = a / b
        On Error GoTo 0
        MessageBox.Show(Result)

Try...Catch...Finally

[edit | edit source]

"Structure error handling" is available with the newer Try...Catch...Finally syntax. Various error conditions are implemented via inheritors of the base Exception class.

    Public Sub Main()
        Dim Result As Integer = 1
        Dim a = 1
        Dim b = 0
        Try
            Result = a / b
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            MessageBox.Show(Result)
        End Try
    End Sub

HINT: If you wish to re-throw an exception inside a Catch block, use the Throw keyword without any arguments (particularly, do not use "Throw ex"). The Throw keyword resets the .StackTrace property of the exception object if an argument is supplied. Throw, without any arguments inside a Catch block will re-throw the error without resetting the .StackTrace property.[1]

  1. Eric Lippert's Blog