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

It says "unexpected word catch in code" am I using catch wrong?

just at a lost i looked it up online and i seem to have it all correct maybe someone can spot what I am missing

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            Console.Write("Enter the number of times to print \"Yay!\": ");

            var entry = int.Parse(Console.ReadLine());
              for(var i = 0; i < entry; i += 1)
            {
                Console.WriteLine("Yay!");
            }

        }            
    }
     catch(FormatException)
     {                  Console.WriteLine("You must enter a whole number.");
                        continue;
     }
}

1 Answer

Justin Horner
STAFF
Justin Horner
Treehouse Guest Teacher

Hello Jonathan,

This step of the challenge wants you to catch the scenario where a user inputs data we don't expect in the console. This means you'll want to try...catch Console.ReadLine to make sure the input is valid.

First you'll need to make sure your entry variable is at a higher scope so it can be accessible via the try catch as well as the for loop.

...
Console.Write("Enter the number of times to print \"Yay!\": ");
var entry = 0;
...

Then place the Console.ReadLine call in a try block

 try 
 {
     entry = int.Parse(Console.ReadLine());
 }

Now you can move your catch block immediately following the try block.

I hope this helps.

Happy Coding :)

Thank You !