c# exception handling does not work

hello,

why is my exception handling not working ??


   public void ExecuteProgram() {

      GetalVerwerking GV = new GetalVerwerking();
     
      ulong getal = IngaveGetal();

      try {
        Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", GV.CijferOmkering(getal));
      } catch (OverflowException) {
        Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", "??? (overflow)");
      }
      Console.WriteLine("Het is {0}EEN palindroom", GV.IsGetalpalindroom(getal) ? "" : "G");
      Console.WriteLine("Druk op en toets om door te gaan. . .");

    } /* ExecuteProgram*/

Open in new window



thanks
kensy11Asked:
Who is Participating?
 
Vel EousConnect With a Mentor Research & Development ManagerCommented:
@kensy11

try
        { and here i should read an STRING type and then convert it to an int for example

           or if i have an int type i should convert it to an string then assign it  to an int ? right ?
 
}

No, that is not required.

string stringVal = Copnsole.ReadLine();
ulong numberVal = Convert.ToIUnt64(stringVal);

is the same as

ulong numberVal = Console.ReadLine();

Basically you are not getting your OverflowException because the value you initially accept from the user fits within the ulong defined memory allocation.  You then perform some arithmetic on the ulong which instead of simply stopping and causing an error when the value exceeds 18446744073709551615, the value is wrapped which is the defined functionality within the .NET Framework.

If you provide ulong getal = IngaveGetal(); with a number greater than 18446744073709551615, you get an overflow exception, because you are attempting to assign a value to getal that does not fit within the defined memory allocation.

However if you provide a value which does fit within the memory allocation you do not get an error and so your code continues.  You are then expecting:

Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", GV.CijferOmkering(getal));

To throw an error as you expect GV.CijferOmkering(getal) to return a value greater than 18446744073709551615.  As explained though, any arithmetic performed on a ulong that causes its value to exceed its limit, does in fact cause the value to "wrap" and therefore start at 0 again.  So attempting to catch an overflow exception on GV.CijferOmkering(getal) always fails, because the number returned is never greater than 18446744073709551615.

ulong maximum = 18446744073709551615;
ulong maximum2 = maximum + 1;
ulong maximum3 = maximum + 2;

The value of maximum2 is 0, the value of maximum3 is 1.

For this reason you cannot rely alone on the OverflowException handler to test that your value exceeds the ulong maximum value, which is why your code is not executing in the manner with which you expect.
0
 
käµfm³d 👽Commented:
Are you entering a value that is bigger than the destination variable can hold? Also, which line gets the data:

ulong getal = IngaveGetal();

Open in new window


--OR--

GV.CijferOmkering(getal)

Open in new window


The former is outside of the try/catch.
0
 
kensy11Author Commented:
the exception handling is for
GV.CijferOmkering(getal)

Open in new window


but when i give a bigger number it doesn't say
Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", "??? (overflow)");

Open in new window


i dont know why
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
käµfm³d 👽Commented:
The largest number a ulong can hold is 18,446,744,073,709,551,615. Are you entering a number larger than that?
0
 
kensy11Author Commented:
yes :p, let say that what i want .

why is it not working ? does anyone know ??
0
 
Vel EousResearch & Development ManagerCommented:
Is your GV.CijferOmkering(getal) doing any arithmetic?  If so it could be that the returned value is not what you expect.

Take a look at the attached snippet, what do you think will happen on line 12?
using System;

namespace EE.ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // what do you think the value is here?
                Console.WriteLine("Resulting output: {0}", ReturnULong(2));
            }
            catch (OverflowException ex)
            {
                Console.WriteLine(string.Format("Overflow Exception: {0}", ex.Message));
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception: {0}", ex.Message));
            }
            Console.ReadLine();
        }

        private static ulong ReturnULong(ulong add)
        {
            return 18446744073709551615 + add;
        }
    }
}

Open in new window

0
 
käµfm³d 👽Commented:
Please post the definition of the CijferOmkering method.
0
 
kensy11Author Commented:
it should give an Overflow  message right ?
0
 
kensy11Author Commented:
CijferOmkering method :
public ulong CijferOmkering(ulong getal) {

      ulong nDel10 = 0;
      byte nRest10 = 0;
      ulong Antwoord = 0;

      if (getal == 0) {
        return 0;

      }

      while (getal > 0 || getal < 0) {

        nDel10 = getal / 10;
        nRest10 = Convert.ToByte( getal % 10);
        Antwoord = (Antwoord * 10) + nRest10;
        getal = nDel10;

      }

      return Antwoord;

Open in new window

0
 
Vel EousResearch & Development ManagerCommented:
it should give an Overflow  message right ?

No, the output on line 12 is the numeric value 1 because; 18446744073709551615 + 2 causes the ulong data type to wrap.  Thus the overflowexception is never caused as the value 2 fits into a ulong data type.

18446744073709551615 + 1 == 0
18446744073709551615 + 2 == 1


0
 
käµfm³d 👽Commented:
So in addition to Tchuki's comment, the place where you should be checking for overflow is, assuming I am correct about what this function does, in the IngaveGetal method. If the user gives a number larger than the value I mentioned earlier, then you will get an overflow.

What you can do in your CijferOmkering method is compare the incoming value against the maximum the value can hold. For example:

public ulong CijferOmkering(ulong getal) {
    if (getal == ulong.MaxValue)
    {
        throw new ArgumentException("Value exceeds allowable limit.", "getal");
    }

Open in new window

0
 
kensy11Author Commented:
I'm sorry, it's still not clear to me,

here is the full program

using System;

namespace ConsAppl1TI18 {
  class ConsCode {
    public void ExecuteProgram() {

      GetalVerwerking GV = new GetalVerwerking();
     
      ulong getal = IngaveGetal();

      try {
        Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", GV.CijferOmkering(getal));
      } catch (OverflowException ) {
        Console.WriteLine("het getal van achter naar voren geschreven is: {0}\n", "??? (overflow)");
      }
      Console.WriteLine("Het is {0}EEN palindroom", GV.IsGetalpalindroom(getal) ? "" : "G");
      Console.WriteLine("Druk op en toets om door te gaan. . .");

    } /* ExecuteProgram*/
    private ulong IngaveGetal() {

      bool ok = false;
      ulong getal = 0;
      string ingave;
      do {
        Console.Write("Geef een getal: ");
        ingave = Console.ReadLine();
        try {
          getal = ulong.Parse(ingave);
          ok = true;
        } catch (FormatException ef) {
          Console.WriteLine("Number Format Exception: {0} in not a valid ulog!", ingave);
        } catch (OverflowException oe) {
          Console.WriteLine("Overflow Exception: {0}", ingave);
        }

      } while (ok != true);

      return getal;

    }/*IngaveGetal*/
  }/*ConsCode*/
}/*ConsAppl1TI18*/

Open in new window



using System;

namespace ConsAppl1TI18 {
  class GetalVerwerking {
    public ulong CijferOmkering(ulong getal) {

      ulong nDel10 = 0;
      byte nRest10 = 0;
      ulong Antwoord = 0;

      if (getal == 0) {
        return 0;

      }

      while (getal > 0 || getal < 0) {

        nDel10 = getal / 10;
        nRest10 = Convert.ToByte( getal % 10);
        Antwoord = (Antwoord * 10) + nRest10;
        getal = nDel10;

      }

      return Antwoord;


    }/*CijferOmkering*/
    public bool IsGetalpalindroom(ulong getal) {

      ulong kopie = getal;

      ulong nDel10;
      byte nRest10;
      ulong Antwoord = 0;

      if (getal == 0) {
        return true;

      }

      while (getal > 0 || getal < 0) {

        nDel10 = getal / 10;
        nRest10 = Convert.ToByte(getal % 10);
        Antwoord = (Antwoord * 10) + nRest10;
        getal = nDel10;
      }

      if (Antwoord == kopie)
        return true;
      else
        return false;
    }/*IsGetalpalindroom*/
  }/*GetalVerwerking*/
}/*ConsAppl1TI18*/

Open in new window



for example in the image it should give Overflow  message

02.jpg
0
 
käµfm³d 👽Connect With a Mentor Commented:
Line 29 in your first code snippet is where an OverflowException can occur, and this is only if the user enters a number larger than what a ulong can hold. However, you are catching OverflowException in line 33 of that same snippet, so outside of the IngaveGetal method, you won't see an OverflowException--because you are not re-throwing the exception.
0
 
santhimurthydConnect With a Mentor Commented:
Hi
Just take a look into the link for what's Overflow exceptionand when it will occur.

http://msdn.microsoft.com/en-us/library/system.overflowexception.aspx

Max value for Ulong is "18,446,744,073,709,551,615", if you give value more than this and you will get the desired error

Try the below wcode snippet

 
try
        {
            string value = Console.ReadLine();
            ulong valu = Convert.ToUInt64(value);
        }
        catch (OverflowException ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();

Open in new window


Attaching the image of the error I have capture
 OverFlow error
In your case value entered is  11,111,111,115,555,555,555 < 18,446,744,073,709,551,615.

That's the reason your not gettimg error
Try with number 18,446,744,073,709,551,616 will throw the error
0
 
kensy11Author Commented:
aha thank you ,   so when i want to check for an Overflow Exception  

i always should use

try
        { and here i should read an STRING type and then convert it to an int for example

           or if i have an int type i should convert it to an string then assign it  to an int ? right ?
 
}
0
 
käµfm³d 👽Connect With a Mentor Commented:
Any time you don't explicitly control the source of incoming data, you should use appropriate exception handling. In other words, if you accept input from user, receive a value from another library, receive input from a network source, etc., then you should check for possible exceptions.
0
 
santhimurthydCommented:
I'm unable to get as what your tring to comment on my explanation.

IN VS, if i plave an vlaue grater than it's max vlaue it won't complie and will throw the below error
Integral constant is too large

Image for your reference

 OverFlow Exception
To capture the error , I have tried to get the max value from User Input using the Stirng and then tried to place in Ulong to get the error captured.

0
 
käµfm³d 👽Commented:
@Tchuki
No, that is not required.

string stringVal = Copnsole.ReadLine();
ulong numberVal = Convert.ToIUnt64(stringVal);

is the same as

ulong numberVal = Console.ReadLine();
Funny, I always thought that ReadLine returned a string, and TMK, there is no implicit conversion between ulong and string. Do you know something about ReadLine that MSDN does not?
0
 
Vel EousResearch & Development ManagerCommented:
@kaufmed

No you are correct in your understanding of how ReadLine() functions.  It was a hasty typo error on my behalf for which you are correct to challenge.  

That line should have been:

ulong numberval = ulong.Parse(Console.ReadLine());

Thank you for highlighting the error.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.