Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Excel VBA: Re-throw error/exception

Tags: error

The current version of Microsoft Excel does not support the new Try/Catch blocks found in VB.net or any other modern programming languages. To handle errors within a procedure the "On Error Goto" statement must be used. When used, VBA expects the procedure to handle the error by either displaying a message visible to the user or just ignore it and continue as before.

However, if you are a Java or .NET developer you might want to restore the state of the application when a error is caught and then re-throw the error to let another part of the application handle it, just like when the "using" statement or throw/catch blocks are applied in C# code. There is no direct way of re-throwing a error in VBA, like throw or throw [Exception] in Java and .NET. The correct way of solving this challenge is to use the Err.Raise method, and specify all the existing error parameters in the following way:

Sub Test()
    On Error GoTo ErrorHandler
   
    ' Do Something   
    Exit Sub
ErrorHandler:
    ' Restore state

    ' Re-throw/Raise existing error   
    Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile,    Err.HelpContext
End Sub

A custom method can be made to simplifying the re-throwing of errors:

' Rethrow
Public Sub ReThrowError(ByVal objError As ErrObject)
    ' Raise   
    Err.Raise objError.Number, objError.Source, objError.Description, objError.HelpFile, objError.HelpContext
End Sub



This post first appeared on LazerWire.com, please read the originial post: here

Share the post

Excel VBA: Re-throw error/exception

×

Subscribe to Lazerwire.com

Get updates delivered right to your inbox!

Thank you for your subscription

×