System.DivideByZeroException does not catch exception

  • Thread starter Thread starter Amin Sobati
  • Start date Start date
A

Amin Sobati

Hi,
I have the following code in my app:

Dim intx As Integer
Dim inty As Integer
Dim intz As Integer
inty = 0
intx = 5
Try
intz = intx / inty
Catch ex As System.DivideByZeroException
MsgBox("Catch")
End Try

But System.DivideByZeroException does not catch the exception. If I use
System.OverflowException it will work.
What's the reason?
Thanks,
Amin
 
But System.DivideByZeroException does not catch the exception. If I use
System.OverflowException it will work.
What's the reason?

The reason is that the / operator performs floating point division,
which doesn't throw a DivideByZeroException but rather returns NaN or
Infinity. If you turn on Option Strict this whould be more visible
since converting the result back to an Integer is a narrowing
conversion.

The solution may be to use the integer division operator \ instead.



Mattias
 
Thanks Mattias!
It was great tip :-)
Amin

Mattias Sjögren said:
The reason is that the / operator performs floating point division,
which doesn't throw a DivideByZeroException but rather returns NaN or
Infinity. If you turn on Option Strict this whould be more visible
since converting the result back to an Integer is a narrowing
conversion.

The solution may be to use the integer division operator \ instead.



Mattias
 
Back
Top