In addition to simply watching for them and screaming "Error!" there are a few other things you should know about error management in Visual Basic programs.
Believe it or not, there are times when you might want to generate runtime errors in your code. In fact, many of the runtime errors you encounter in your code occur because Microsoft wrote code in the Framework Class Libraries (FCLs) that specifically generates errors. This is by design.
Let's say that you had a class property that was to accept only percentage values from 0 to 100, but as an
Integer data type.
Private StoredPercent As Integer Public Property InEffectPercent( ) As Integer Get Return StoredPercent End Get Set(ByVal value As Integer) StoredPercent = value End Set End Property
Nothing is grammatically wrong with this code, but it will not stop anyone from setting the stored percent value to either 847 or −847, both outside the desired range. You can add an
If statement to the
Set accessor to reject invalid data, but properties don't provide a way to return a failed status code. The only way to inform the calling code of a problem is to generate an exception.
Set(ByVal value As Integer) If (value < 0) Or (value > 100) Then Throw New ArgumentOutOfRangeException("value", _ value, "The allowed range is from 0 to 100.") Else StoredPercent = value End If End Set
Now, attempts to set the
InEffectPercent property to a value outside the 0-to-100 range will generate an error, an error that can ...