LOG IN

Forgot Your Password?


Incorrect login or password

SIGN UP



Existing user?

Forgot Password


Existing user?

Exception handling

 

Exception handling

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

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

"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

Source: https://en.wikibooks.org/wiki/Visual_Basic_.NET/Exception_handling


 << Previous  Next >>