Joseph Nields
Joseph Nields

Reputation: 5661

Why is this CInt function call *not* throwing an error?

I'm just curious, really.

There was some code that wasn't handling empty strings before converting, essentially calling

Dim StringToConvert As String = ""
Dim a As Integer = CInt(StringToConvert)

Rather then something like

Dim StringToConvert As String = ""
Dim a As Integer = CInt("0" & StringToConvert)

and so it makes sense that it would throw an error...

What I don't understand is that this wasn't throwing an error on my machine when I was debugging. But it does throw an error when compiled!

Here is what calls the CInt function and only sometimes throws an error:

Public NotInheritable Class SomeForm
    Inherits Windows.Forms.Form

    Private Sub TextBox_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles TextBox.LostFocus
        StaticHolderClass.StaticMethod(DirectCast(sender,TextBoxBase))
    End Sub

End Class

Public NotInheritable Class StaticHolderClass

    Public Shared Sub StaticMethod(ByVal sender As Windows.Forms.TextBoxBase)
        sender.Text = Format(CInt(sender.Text),"#,#")
    End Sub

End Class

Does anyone know why this would happen?

Upvotes: 1

Views: 505

Answers (1)

xpda
xpda

Reputation: 15813

In VB, occasionally when an error is encountered during form initialization, it doesn't get reported properly. Sometimes the error is not flagged at all, and sometimes it appears to be from a different location. For example, in the following code (on my system), an error is thrown with the button click and not the form load:

Public Class Form1
Dim k As Integer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
k = CInt("")
End Sub

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
k = CInt("")
End Sub

End Class

It seems to depend on the environment, so "your results may vary". You can work around this sometimes by using the shown event rather than load.

Upvotes: 2

Related Questions