Division by Zero, Exception or Not?

  • Thread starter Thread starter Sean Kirkpatrick
  • Start date Start date
S

Sean Kirkpatrick

Sometimes, when I think I understand something and try to explain it to
someone else, I realize that I don't understand it at all.

Consider:

Dim i As Integer
Dim d As Double
Dim a As Integer = 3
Dim b As Integer = 0

' case 1
Try
TextBox1.Text = a / b
Debug.WriteLine(i)
Catch ex As Exception
TextBox1.Text = "Uh Oh"
End Try

' case 2
Try
TextBox1.Text = a \ b
Debug.WriteLine(d)
Catch ex As Exception
TextBox1.Text = "Uh Oh"
End Try

' case 3
Try
i = a / b
Debug.WriteLine(i)
Catch ex As Exception
TextBox1.Text = "Uh Oh"
End Try

' case 4
Try
d = a \ b
Debug.WriteLine(d)
Catch ex As Exception
TextBox1.Text = "Uh Oh"
End Try

case 1 puts "Infinity" in TextBox1 but the other three throw an
exception and put "Uh Oh" there instead. This makes no sense to me. At
first thought, I would expect a div 0 error to ALWAYS result in an
exception as in 2, 3, and 4.

But then, maybe there's special behavior since VB "knows" that the
assignment is to a text box and so it gives a "friendly" answer for 1,
but why doesn't it do that for 2?

This seems VERY inconsistent behavior. If not, why?

Sean
 
Try to do the same thingy with option strict on and there is your answer :-)

regards

Michel Posseth
 
You have the operators confused.

\ is the Integral division
/ the floating point


a / b, gives infinity
a \ b, gives a div-zero error


case 1

a / b -> Infiinty Infinity.ToString() = "Infinity"


Case 2

a \ b DIVZERO


case 3

int i = a/b ; tryng to assign Infinity to integer - error


case 4

double d = a \b integral div by 0 error



NOTES:

You should turn on Option Strict
It will flag case 3 as an invalid assignment.


hth
Alan
 
Back
Top