Kapé
Kapé

Reputation: 4781

How to rethrow error in VBA

When there's an error I would like to do some cleanup and then let the error flow up so that it's handled globally.

In C# I would do a try finally but that is not possible with VBA, only On Eror GoTo <mylabel>.

How can I rethrow the error properly when caught in the label?

Is it only possible calling Err.Raise again with all properties, no throw like keyword exists?:

Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext

Upvotes: 10

Views: 3166

Answers (2)

david
david

Reputation: 2638

That is the correct method, but no, you don't have to re-state all the err properties. The values are retained:

err.raise Err.Number

is the same as

Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext

https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/raise-method

It can be more complex if you are throwing out of a class module. By default, the err object of a class module is caught and re-created, so depending on how it is declared, properties may be replaced.

Upvotes: 5

BR_DataMiner
BR_DataMiner

Reputation: 157

I think that you should use ON ERROR GOTO...

And continue your error handling inside the "next_step"

For example:

Sub test()
    'IF OCCOUR ERROR INSIDE THIS BLOCK THE ERROR CONTINUE IN "next_step"
    On Error GoTo next_step

    If Err.Number = 10 Then
        Msgbox"Error!"
    End If

    next_step:
    'YOU CAN CONTINUE YOUR CODE HERE!!

End Sub

Upvotes: -2

Related Questions