Partilhar via


Visual Basic Concepts

Coding Robust Initialize and Terminate Events

Classes you define in Visual Basic, whether class modules, UserControls, or UserDocuments, have built-in Initialize and Terminate events. The code you place in the Initialize event will be the first code executed when an object is created.

For example, in the first part of the following code fragment the Widget class of the SmallMechanicals component sets the value of its read-only Created property at the moment an object is created.

' Code for the component's Widget class module.
' Storage for the read-only Created property.
Private mdatCreated As Date

' Implementation of the read-only Created property.
Public Property Get Created() As Date
   Created = mdatCreated
End Property

' Set the value for the read-only Created property when
' the object is created.
Private Sub Class_Initialize()
   mdatCreated = Now
End Sub

' Code for the client application.
Private Sub cmdOK_Click()
   Dim wdgX As New SmallMechanicals.Widget
   ' Display date/time object was created.
   MsgBox wdgX.Created
End Sub

In the last part of the code fragment, the client creates a Widget object. The variable wdgX will contain the reference to the Widget object; it is declared As New, so the Widget is created at the first use of wdgX in code. When the MsgBox function is executed, the Widget is created, and the very first code it executes is its Class_Initialize event procedure. When the read-only Created property of the newly created Widget is evaluated, its value has already been set, and therefore MsgBox correctly displays the time the Widget was created.

Errors that occur in the Class_Initialize event procedure are returned to the point in the client at which the object was requested. Thus, adding the following line to the Widget’s Class_Initialize event procedure will cause error 31013 to occur on the client’s MsgBox statement.

   Err.Raise Number:=31013

Handling Errors in the Terminate Event

The Terminate event is the last event in an object’s life. You can place cleanup code in the Class_Terminate event procedure, and this code will be executed when the last reference to the object has been released, and the object is about to be destroyed. Complex objects that contain dependent objects should release references to their dependent objects in the Terminate event.

Errors in the Terminate event require careful handling. Because the Terminate event is not called by the client application, there is no procedure above it on the call stack. This means that an unhandled error in a Terminate event will cause a fatal error in the component.

Important   For in-process components, your fatal error is your client’s fatal error. Because the component is running in the client’s process, the client application will be terminated by a component’s fatal error.