What’s Wrong with That?


It happens. Objects fall apart. You can’t make a class hierarchy without breaking methods. Code isn’t always a bowl of cherries.


When things go wrong, what can you do? Like other languages, Visual Basic offers many alternatives, most of them wrong. Let’s look at some of the more common strategies, pick one to emphasize in this book, and explain some techniques for making it work.


Any discussion of error handling has to consider two sides. What should your components do with errors? And what should clients of those components do with whatever you do with errors? In this section, we’ll be wearing the hat of the component creator, but of course, any civilized programmer has to consider the effect on the client side.

iSecondsToday = VBA.Timer

Does this give you an idea of how to enhance rather than replace library functions? Here’s how I enhanced the Hex function to add leading zeros:

Function Hex(ByVal i As Long, Optional iWidth As Long = 0) As String
If iWidth <= 0 Then
Hex = VBA.Hex$(i)
Else
Hex = Right$(String$(iWidth, “0”) & VBA.Hex$(i), iWidth)
End If
End Function

You can see more of my improved procedures in BETTER.BAS. Most of them follow the same pattern. Use optional arguments to add new features to an existing procedure. If the user doesn’t provide the argument, use the original procedure. Otherwise, call the original procedure for base functionality and add your own embellishments.


You can override library procedures because of Visual Basic’s name space priority list. It starts with your project, goes on to the VB, VBA, and VBRUN libraries, and continues with other loaded controls and components. That’s why I don’t have a global class named BETTER.CLS in the VBCore component. The standard Visual Basic libraries would always override anything in the component. If you want better Basic procedures, you must include the standard module BETTER.BAS directly in your project.


Although replacing standard procedures is a cool trick, it’s kind of a questionable programming practice and in real life I rarely use BETTER.BAS. Instead, I use FmtHex (in UTILITY.BAS) rather than the Hex function. I use ProfileStart and ProfileStep in DEBUG.BAS rather than the Timer function.