Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Basics (Retired) Perfect Final

Idan Amar
Idan Amar
798 Points

input validation with try and catch

trying to do the exercise, but the compiler always comes with an error, i dont see any problem here, besides i dont get why you need the try and catch if you can just break when the user enter a non string variable..

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            string yay = Console.ReadLine();
            if ( yay.GetType() != string ) {
                            Console.Write("You must enter a whole number.");
                break;}
            try {
            int yaytimes = int.Parse(yay);
            while (yaytimes != 0) {
                Console.Write("Yay!");
                yaytimes--;       }
           }
            catch(FormatException)
                {
                    Console.WriteLine("That is not valid input.");
                   continue;
                }

        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,096 Points

The response from Console.Readline is always a string.

So it's not useful to test it for type.

Other issues:

  • you used "Write" where you probably intended "WriteLine"
  • you must use the exact error message(s) given in the instructions
  • you can only use "break" or "continue" inside a loop (plus the program should end after an error)
Idan Amar
Idan Amar
798 Points

ok, thank you for your response, but how can i complere the task if it not useful to test it for type?

Steven Parker
Steven Parker
231,096 Points

Using try and catch are all you need for task 2 of the challenge.