שתף באמצעות


Error Handling when dividing by zero in VB,NET (Visual Studio Express 2015)

Question

Tuesday, August 11, 2015 7:10 PM

Module Module1

    Sub Main()

        Dim x As Integer
        Dim y As Integer
        
        Console.Write("Enter value of x: ")
        x = Console.ReadLine
        Console.Write("Enter value of y: ")
        y = Console.ReadLine

        Try

            Console.WriteLine("x / y: " & x / y)
            Console.WriteLine("x \ y: " & x \ y)
            Console.WriteLine("x Mod y: " & x Mod y)

        Catch ex As Exception

            Console.WriteLine(ex.Message)

        End Try

        Console.ReadLine()

    End Sub

End Module

Trying to understand the basics of error handling in VB.NET. I ran the above code in Visual Studio Express 2015. Currently using Windows 10. The issue is when entering y = 0. The result I got (irrespective of the input value of x) at first was :

=======================================

x / y = 8

Attempting to divide by zero.

=======================================

Why does the code return the first line as a result?

I then declared x and y as Double and got the following handling message. 

=======================================

Conversion from string "x / y = 0" to type Double is not valid.

=======================================

Funnily enough, when I declared x and y as integer again and ran the code I got the same error handling message as when declared as Double. I have tried closing and launching VSE 2015 (just in case it is a random glitch) but the error handling message is constantly the one displayed in image. Could anyone please help me understand what may be causing this and why did I the code initially return x / y = 8 ?

All replies (9)

Tuesday, August 11, 2015 10:48 PM ✅Answered

I agree with Dave299, turn option strict on, and division by 0 when the data type is double gives infinity (1.#INF).  If you are using zero division to learn about exception handling, then one thing I would suggest, be specific in your catch blocks.  In the specific case of divide by zero that would look like this:

        Dim xd As Double = 42
        Dim yd As Double = 0
        Dim ansd As Double = xd / yd

        Dim xi As Integer = 42
        Dim yi As Integer = 0

        Try
            Dim ansi As Integer = xi \ yi
        Catch dbz As DivideByZeroException
            Stop
        End Try

In the real world it would be bad form to ever have to catch this particular error.  Try-Catch is for errors that can't be avoided,.

"Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." - MSDN User JohnWein    Multics - An OS ahead of its time.


Wednesday, August 12, 2015 3:31 AM ✅Answered

Thanks Dave 299. I was expecting a message which would show Infinity. I cannot explain the error messages I got. Will follow your suggestion to Option Strict On to investigate this.


Tuesday, August 11, 2015 7:32 PM

  The error is telling you exactly what the problem is,  you can not divide any number by 0.  You can even try that in windows calculator and it will tell you that you can not divide a number by 0.  You will have to use a While loop in your code to make the user keep entering a number if they try entering 0 for y.

 Or you can just use an If Then statement so that your code does not execute the calculations if they enter 0 for y.

 You need to convert the Strings from the 2 ReadLine,  lines to Integer Types.  You can use the CInt function or the Int32.TryParse method to do that.  The CInt function will throw an exception if you enter anything other than a number though.  The TryParse method would be the safe way to go.

x = CInt(Console.ReadLine)

 These lines,

Console.WriteLine("x / y: " & x / y)

Should look like this,  with the x/y surrounded by brackets and converting the result to a String.  Same with the (x Mod y) too.

Console.WriteLine("x / y: " & (x / y).ToString)

If you say it can`t be done then i`ll try it


Tuesday, August 11, 2015 10:00 PM | 1 vote

The result I got (irrespective of the input value of x) at first was :

x / y = 8

Attempting to divide by zero.

I then declared x and y as Double and got the following handling message.

Conversion from string "x / y = 0" to type Double is not valid.

Are you sure that the code you have posted is the code which produced these results.  I have tried your code as posted in VS2015 and cannot verify these results.  Attempting to divide by zero gives a result of Infinity.

Both of the results you show include an equals (=) sign.  But there is nowhere in your code that can produce that.  Also the only place in your code which converts a string to a double is when the user enters a number and so the only way you can get the second error is if the user enters "x/y=0".

It would be a good idea to turn Option Strict On and fix the errors you then get before investigation this further.


Wednesday, August 12, 2015 3:45 AM

Thanks dbasnett. I simply followed the code I found in a tutorial and in that video it did return Infinity as a result. Thinking about it, the code in that video was run in VS 2013.

============================================================

In the real world it would be bad form to ever have to catch this particular error.  Try-Catch is for errors that can't be avoided,.

============================================================

Will definitely keep this in mind whilst coding.


Wednesday, August 12, 2015 4:22 AM

Thanks IronRazerz. Firstly, I am aware that dividing by zero should return infinity. What was quite unexpected was that "x / y = 8" was printed in the console window as a result followed by the statement "Attempting to divide by zero" when run in VS 2015. This code was run in VS 2013 in a tutorial that I watched online and worked fine. I do concur that it would be better  to prevent user from inputting y as zero. However, in this particular program I wanted it to return an error to the screen to inform the nature/cause of the error and hence was expecting something along the line of "x / y = Infinity".

Did you catch the part where I mentioned declaring as Double resulted in a different error handling message and reverting to Integer would then always return the same error handling message as when declared as Double? Again, I'm not solely interested in getting the code to function. I wanted to understand why it was "behaving" in this particular way.  Dave 299 (refer to his response) did not encounter the same issues I did.

Thanks for the suggestions you have made in regard to the code. That explanation was very informative.


Tuesday, April 26, 2016 3:19 AM

I realise this thread is a few months old, but I came across it when trying to understand why I was seeing "x / 0 = 8", and I thought I'd post my findings in case it helps anyone else. The "8" displayed as the ToString representation of the result isn't really the number 8, but a ToString representation of the infinity symbol. There is no DivideByZeroException occurring for the calculation. 

The behaviour seems to be specific to Windows 10 machines. I'm running the latest .NET Framework. Here's a program that demonstrates the behaviour. Notice the result of the "h" variable, which shows the character code is unicode 8734 (0x221E), which is the infinity symbol.

class Program
{
    static void Main(string[] args)
    {
        double a = 1000;
        double b = 0;
        double c = a / b;
        bool d = (c == 8);
        bool e = double.IsInfinity(c);
        string f = c.ToString();
        bool g = (f == "8");
        int h = (int)f[0];
        char i = '\u221E'; // = 8734 decimal
        bool j = (i == f[0]);

        System.Console.WriteLine("a / b = " + a / b);
        System.Console.WriteLine("c = " + c);
        System.Console.WriteLine("d = " + d);
        System.Console.WriteLine("e = " + e);
        System.Console.WriteLine("f = \"" + f + "\"");
        System.Console.WriteLine("g = " + g);
        System.Console.WriteLine("h = " + h);
        System.Console.WriteLine("i = \"" + i + "\"");
        System.Console.WriteLine("j = " + j);

        System.Console.WriteLine("OS Version = " + System.Environment.OSVersion);
        System.Console.WriteLine("OS 64-bit = " + System.Environment.Is64BitOperatingSystem);
        System.Console.WriteLine("Process 64-bit = " + System.Environment.Is64BitProcess);
        System.Console.WriteLine(".NET Version = " + System.Environment.Version);
    }
}

These are the results on my computer:

a / b = 8
c = 8
d = False
e = True
f = "8"
g = False
h = 8734
i = "8"
j = True
OS Version = Microsoft Windows NT 6.2.9200.0
OS 64-bit = True
Process 64-bit = False
.NET Version = 4.0.30319.42000

Tuesday, April 26, 2016 10:54 AM

Have you reported this as a bug?

"Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." - MSDN User JohnWein    Multics - An OS ahead of its time.


Tuesday, April 26, 2016 8:44 PM

I've submitted it as a bug here: https://connect.microsoft.com/VisualStudio/feedback/details/2637564