Search notes:

VBA: the Err object

The err object is a singleton: exactly one instance of it is alway present. It has global scope. (Technically, it is a global class module.)
The err object is reset with the on error statement.

Methods and properties

Clear()
Description
HelpContext
HelpFile
LstDllError
Number
Raise()
Source

Catch exception, show properties

The following simple example divides 42 by 0, which, of course, will throw an error.
In the case of an error, the error handler (on error goto failed and failed:) will then print the Err object's properties:
option explicit

sub main() ' {

     debug.print ("25/5 = " & divide(25, 5))
     debug.print ("42/0 = " & divide(42, 0))

end sub ' }

function divide(a as double, b as double) as double ' {

  on error goto failed

    divide = a / b

  exit function

  failed:
     debug.print("division failed")
     debug.print("  err.description = " & err.description)
     debug.print("  err.number      = " & err.number     )
     debug.print("  err.source      = " & err.source     )

end function ' }
Github repository about-VBA, path: /objects/err/show.bas

Raising a user error

An error (what other programming languages possibly might call an exception) is raised with error.raise:
err.raise errorNumber, source, description, helpFile, helpContext
All parameters except errorNumber are optional.
option explicit

sub main() ' {

  on error goto failed

    debug.print("42/6 = " & divide(42, 6))
    debug.print("55/0 = " & divide(55, 0))
    debug.print("13/9 = " & divide(13, 9))

  failed:
    debug.print("Failed: " & err.description)

end sub ' }

function divide(a as double, b as double) as double ' {

    if b = 0 then
       call err.raise(1000, "divide", "b must not be zero")
    end if

    divide = a / b

end function ' }
Github repository about-VBA, path: /objects/err/raise.bas

Clearing the err object

The error object can be cleared with err.clear().
err.clear is invoked behind the scenes at any of the following events:

See also

on error goto, on error resume next.
The err object is also returned from the VBE7 runtime function rtcErrObj().
The MacroError object in Access's Object Model.
The collection object.
The JavaScript error object.
The Excel Error object.

Index