Search Tools Links Login

How to embed an error code in a standard function return


I have read many accounts in various books and articles about how it would be nice to be able to return an error code with every function return.

It's fairly easy to achieve this. Simply create a User-Defined-Type (or class) called tReturn (or whatever) in a global module (assuming the use of a UDT).

'---------------------------------------------
Type tReturn
    Value as Variant
    Error as Integer
End Type
'---------------------------------------------

Creating a class (which I personally prefer utilizing in my own code) allows for fairly sophisticated error handling by embedding functions within the class to resolve the errors without needing to stick alot of error-handling code all over the place.

Usage

Make each function of type tReturn.

'---------------------------------------------
Public Function MyFunc(arg1, arg2) as tReturn
'---------------------------------------------

When coding the function body, if an error occurs simply assign a non-zero value to the ".Error" item in the return value

'---------------------------------------------
Public Function MyFunc(arg1, arg2) as tReturn
   ...
   MyFunc.Error = 5 'Some Error
          (or)
   MyFunc.Error = Err
   ...
End Function
'---------------------------------------------

This way, you can always tell if an error has occured by checking the existence of an error in the return value

'---------------------------------------------
   Dim MyReturn as tReturn
   ...
   MyReturn = MyFunc(3,8)
   If Not MyReturn.Error Then
      nSomeVariable = MyReturn.Value
   End If
   ...
'---------------------------------------------

If you create tRetrun as a class (cReturn or whatever), you can make .Value as the default property and code it this way:

'---------------------------------------------
   Dim MyReturn as New cReturn
   ...
   MyReturn = MyFunc(3,8)
   If Not MyReturn.Error Then
      nSomeVariable = MyReturn
   End If
   ...
'---------------------------------------------

About this post

Posted: 2019-08-25
By: BobWallace
Viewed: 201 times

Categories

Visual Basic 6

Attachments

No attachments for this post

Special Instructions

This code originally appeared on AndreaVB.com, and has been republished here with the permission of Andrea Tincani.


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.