System.DivideByZeroException does not catch exception

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
 
M

Mattias Sjögren

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
 
A

Amin Sobati

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Removing character 1
All combinations 7
cell has decimal value returns whole number, why? 2
vb6 to C# 5
VB6 to C# 1
Barcode Interleaved 2/5 through VBA 3
Array Questions 3
Splitter control location 2

Top