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

Madeleine Barois
Madeleine Barois
1,485 Points

try{} and catch(FormatException){} placement

I can't figure out where to put the try{} and catch(FormatException){}.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            //Create a tracking variable that is set to zero
            var tracking = 0;

            //Prompt user to enter a number
            Console.Write("Enter the number of times to print \"Yay!\": ");

            //store entry in a variable
            var entry = Console.ReadLine();

            while(true) //Repeat the print
            {    
                try
                {               
                    //Convert variable to an integer
                    var repeats = int.Parse(entry);

                    if (tracking >= repeats)  //if the tracking varialbe is >= entry variable, break the loop
                        {
                            break;
                        }

                    //Print Yay to the screen and add 1 to tracking variable 
                    Console.WriteLine("\"Yay!\"");
                    tracking += 1;
                }

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

2 Answers

Steven Parker
Steven Parker
231,222 Points

The try looks good but the exception should exit the loop instead of continuing it. That would cause it to get stuck in the loop, printing the error message over and over.

Also, while not essential to passing the challenge, it might make more sense to do the numeric conversion just once, before the loop starts.