Passing Errors in Class Modules

Although class objects can respond to errors that occur within them, they should not, because doing so forever binds the object to a specific implementation.

Class objects don't spontaneously leap into existence; they must be instantiated by other code. The code that creates the class is what implements the broader function, only calling the class for a smaller part of it, and so it should be the one to respond to errors that occur within the class object. By definition, any error in the class object is an error in the broader function. This is shown in Figure 12-14.

Figure 12-14

So what do we do? Our class must pass the error back to the calling code using the Err.Raise method. Whether it's a VBA error or a custom-defined error, our class procedures must trap the error and just pass it along. All that the calling code has to do is test for it. The following two examples demonstrate how you can do this.

Example 1

Public sub TestErrors()

Dim obj As clsMyClass

Set obj = New clsMyClass Obj.SomeMethod

1 Handle the error End If End Sub

Example 2

Public sub TestErrors()

Dim obj As clsMyClass On Error Goto TestErrors_Err

Set obj = New clsMyClass Obj.SomeMethod 'Error occurs in here

TestError_Exit:

On Error Resume Next Set Obj = Nothing Exit Sub

TestErrors_Err:

'Handle the error Resume TestErrors_Exit End Sub

0 0

Post a comment