vb.net-2010overflowexception

Arithmetical Exceptions


I'm in a programming high school course, and my assignment is to write a program that uses: OverflowException, or NotFiniteNumberException. It has to be arithmetical and I've tried everything I can think of, but I can't seem to get it to print correctly so I'm assuming the problem is with my code. This is one of the things I've tried:

Module Module1

Sub Main()
    Dim A As Integer = Integer.MaxValue
    Dim B As Integer = A + 1
    Try
        Console.WriteLine("The answer is: ", B)
        Console.ReadLine()
    Catch C As OverflowException
        Console.WriteLine("B is greater than the maximum value ")
        Console.ReadLine()
    End Try
End Sub

End Module

When I do this, it does give an error message, but it says "Unhandled Exception", and not "B is greater than the maximum value". Obviously, I don't know why it does this, so any information would be a big help. If it would be easier to suggest a way to write one with NotFiniteNumberException that would work also, I just thought I'd show what I've tried, thanks!


Solution

  • These two lines can never throw any exceptions:

    Console.WriteLine("The answer is: ", B)
    Console.ReadLine()
    

    This line, however, can:

    Dim B As Integer = A + 1
    

    You should include the latter inside the Try/Catch block, something like this:

    Dim B As Integer
    Try
        B = A + 1 
        Console.WriteLine("The answer is: ", B)
        Console.ReadLine()
    Catch C As OverflowException
        Console.WriteLine("B is greater than the maximum value ")
        Console.ReadLine()
    End Try
    

    Notice there you are not using the value of B, so you can include declaration of B inside the Try/Catch. I put it outside on purpose, this is generally what you want to do in serious applications. You would generally have an object in certain state, trying to change its state. If your code fails, you can display current state of the object and notify that attempted action failed to execute. Think of it as best practice advice.