-1

Total noob here, still trying to learn C# ... not sure where this exception is being thrown. I'm not seeing it in output and the program compiles and runs flawlessly.

EDIT: By flawlessly I mean the code compiles, runs, does what it needs to do, and exits appropriately without crashing.

EDIT2: More information: this is for an online class and I don't see the exception thrown in visual studio but when I paste my code into their on site answer block and have it check the work it throws the exception which is making it difficult to locate the source. The output window in VS isn't returning the ArgumentNullException.

    static void Main()
    {
        Console.Write("Enter the number of times to print \"Yay!\": ");
        while (true)
        {
            try
            {
                string times = Console.ReadLine();
                int repeater = int.Parse(times);
                while (repeater > 0)
                {
                    Console.WriteLine("Yay!");
                    repeater--;
                }
                break;
            }
            catch (FormatException)
            {
                Console.WriteLine("You must enter a whole number!");
            }
        }
        Console.ReadLine();
    }

EDIT3: FINALLY got this error from the school's compiler:

System.ArgumentNullException: Value cannot be null.
Parameter name: String
  at System.Number.StringToNumber (System.String str, NumberStyles options, System.NumberBuffer& number, System.Globalization.NumberFormatInfo info, Boolean parseDecimal) [0x00054] in /builddir/build/BUILD/mono-4.4.2/external/referencesource/mscorlib/system/number.cs:1074 
  at System.Number.ParseInt32 (System.String s, NumberStyles style, System.Globalization.NumberFormatInfo info) [0x00014] in /builddir/build/BUILD/mono-4.4.2/external/referencesource/mscorlib/system/number.cs:745 
  at System.Int32.Parse (System.String s) [0x00000] in /builddir/build/BUILD/mono-4.4.2/external/referencesource/mscorlib/system/int32.cs:120 
  at Treehouse.CodeChallenges.Program.Main () <0x41076f10 + 0x0004e> in :0 
  at MonoTester.Run () [0x00197] in MonoTester.cs:125 
  at MonoTester.Main (System.String[] args) [0x00013] in MonoTester.cs:28 

Exercise instructions: Add input validation to your program by printing “You must enter a whole number.” if the user enters a decimal or something that isn’t a number. Hint: Catch the FormatException.

A. Sellite
  • 39
  • 4
  • 3
    [int.Parse](https://msdn.microsoft.com/en-us/library/b3h1hf19(v=vs.110).aspx) will throw a ArgumentNullException if passed null. – stuartd Sep 19 '16 at 16:02
  • 1
    I don't know if you can say the application runs flawlessly if these sorts of exceptions are still being thrown... – Broots Waymb Sep 19 '16 at 16:05
  • 1
    Surely the debugger told you exactly what line this happened on and what the issue was? I mean come on, this is so basic it's silly – Liam Sep 19 '16 at 16:05
  • 1
    Also, don't quite feel like writing up an answer at the moment, but you may want to look at `Int32.TryParse`... – Broots Waymb Sep 19 '16 at 16:06
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Liam Sep 19 '16 at 16:07
  • 1
    The only way to reproduce the problem is typing CTRL+Z at the input otherwise, as far as I can tell, this code cannot produce that exception – Steve Sep 19 '16 at 16:11
  • 1
    How can it be a duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) when OP gets an `ArgumentNullException`? Have any of you down/close voters actually looked at the code? – Good Night Nerd Pride Sep 19 '16 at 16:14
  • @Liam ArgumentNullException is not a NullReferenceException. The difference is subtle but they are not the same – Steve Sep 19 '16 at 16:14
  • 1
    [Stack Overflow in a nut shell](https://www.youtube.com/watch?v=kMjqlVcLCmg) – LarsTech Sep 19 '16 at 16:22
  • @A.Sellite don't be too concerned with remarks that you find offending. This happens everywhere online and you should only hope to get in touch with kind people but be prepared for the unkind ones. Back to your problem. If you run this code inside Visual Studio and get the exception you should see the line where it happens. What do you type for the input? – Steve Sep 19 '16 at 16:24
  • Steve, this is for an online class and I don't see the exception thrown in visual studio but when I paste my code into their on site answer block and have it check the work it throws the exception which is making it difficult to locate the source. The output window in VS isn't returning the ArgumentNullException. – A. Sellite Sep 19 '16 at 16:31
  • Are you sure about the output requested in the exercise? Post the exercise at least we understand where the problem is. – FeliceM Sep 19 '16 at 17:22
  • Felice, I will post the exercise and add it to the question now. – A. Sellite Sep 19 '16 at 17:30

3 Answers3

1

Try:

if (times != null) {
   int repeater = int.Parse(times);
   // rest of your code here
} else {
   // deal with the null, you could just break and ask for more input
}
dahui
  • 1,978
  • 2
  • 15
  • 35
  • Thank you for trying to help. This answer again, compiles and runs successfully, but doesn't fix whatever the stupid class compiler is seeing as an error. – A. Sellite Sep 19 '16 at 16:49
  • @A.Sellite, are you sure? The exception stacktrace from your question clearly shows that the exception is coming from `int.Parse(times)` when `times` is `null`. There's literally no way this exception can still occur when you use dahui's solution correctly. Maybe the course system throws a different exception after this fix? – Good Night Nerd Pride Sep 20 '16 at 09:36
  • Maybe, I'd check again but I already submitted my broken program which it excepted so I can't go back and check... I ran this code through VS though and it worked fine. I feel like I understand how the fix helped though so that gave me a tool to use in the future! :) – A. Sellite Sep 20 '16 at 14:26
1

I'd like to take a moment and thank everyone for their contributions to my question. It definitely helped me work my way to a 'correct' answer... For those interested here is the code that the school's compiler ended up accepting as a 'correct answer'. It isn't a well written program and when exceptions are thrown (especially the one this question is about) the program just quits. I don't really know how to make it prompt the user for input again when trying to deal with the null but it is what it is, the project is finished and my code was excepted. If you'd like to provide some insight feel free.

static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            while (true)
            {
                string times = Console.ReadLine();
                if (times != null)
                {
                    try
                    {
                        int repeater = int.Parse(times);
                        if(repeater < 0)
                        {
                            Console.WriteLine("You must enter a positive number.");
                            return;
                        }
                        else
                        {
                            while (repeater > 0)
                            {
                                Console.WriteLine("Yay!");
                                repeater--;
                            }
                            break;
                        }
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("You must enter a whole number!");
                    }
                }
                else
                {
                    return;
                }
            }
            Console.ReadLine();
        }
A. Sellite
  • 39
  • 4
  • 1
    I think this solution is OK. The code could be restructered to be easier to read (if you want help with that then check out [codereview.stackexchange.com](http://codereview.stackexchange.com)), but it makes sense to quit the program when `times` is `null`. Consider that this only can happen when the user presses `Ctrl`+`Z`, which basically [means that the user wants to exit](https://msdn.microsoft.com/en-us/library/system.console.readline(v=vs.110).aspx). I think the course system tested how your program handles all possible inputs, i.e. a valid integer, an invalid string, and `Ctrl`+`Z`. – Good Night Nerd Pride Sep 20 '16 at 11:00
  • I didn't even know ctrl-z could be used in a console application. Thanks for teaching me that. Also thank you for providing the link to codereview. That's a really good resource that I think I'll be taking serious advantage of in the near future. – A. Sellite Sep 20 '16 at 14:28
0

Replace:

int repeater = int.Parse(times);

with:

int repeater;
int.TryParse(times, out repeater);

It could be that int.Parse(times) is failing because times is null. Post the stack trace for more help.

Liam
  • 22,818
  • 25
  • 93
  • 157
Sooey
  • 39
  • 5
  • Please read [How do I format my code blocks?](http://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) – Liam Sep 19 '16 at 16:09
  • Sorry Liam about the formatting. In the code above, if it is not parsed repeater will be 0 and the code will continue. – Sooey Sep 19 '16 at 16:14
  • Also - I'd advise against while(true) in general. – Sooey Sep 19 '16 at 16:15
  • Liam - thanks for the link! ... i was wondering how to do this. – Sooey Sep 19 '16 at 16:20
  • Liam - you docked me because of a formatting issue (and I'm learning to post answers) but I gave the best answer. This doesn't seem fair. In my solution the code continues and then breaks as expected. – Sooey Sep 19 '16 at 16:41
  • Sooey, thanks for taking the time to answer and not berating me. I appreciate it. – A. Sellite Sep 19 '16 at 16:43
  • Ha ha! I know how you feel - A. Sellite. Did you get a chance to try the solution? Also, if you look through the stack trace usually it will point you to the problem. Also, the int.TryParse returns a boolean which you can use in place of a try..catch block by checking the result. Try/catch can be heavy for your scenario. If the result is false then you can inform the user to enter valid information. – Sooey Sep 19 '16 at 16:55
  • I will attempt to use the int.TryParse. I know that this is a stupid question, and I'm sorry, but where is the Stack Trace? Is that not displayed in the standard output window? I know how to read error messages when the program crashes but it isn't crashing either. – A. Sellite Sep 19 '16 at 17:05