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 trialIdan Amar
798 Pointsinput 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..
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
231,269 PointsThe 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
798 PointsIdan Amar
798 Pointsok, thank you for your response, but how can i complere the task if it not useful to test it for type?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsUsing
try
andcatch
are all you need for task 2 of the challenge.