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

C# Basic Course Having trouble with a loop

In the C# Basic Course, I'm getting a loop error: "No enclosing loop out of which to break or continue" in or around the catch statement.

Not sure what this error means or how to fix it.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
        int counter = 0;
        while (true)     
        Console.Write("Enter the number of times to print \"Yay!\": ");  
        var entry = Console.ReadLine();
              try
              { 
               int userInput = int.Parse(entry);
                 while (userInput > counter)
                 {
                 Console.WriteLine("Yay!");
                 counter = counter + 1;
                 continue;
                 }
               } //try
                   catch(FormatException)
                   {    
                   Console.WriteLine("You must enter a whole number.");
                   continue;
                   }
            Console.WriteLine("Goodbye");  
       } //static
    } //class
} //namespace

1 Answer

Benjamin Lange
Benjamin Lange
16,178 Points

This error is telling you that you are trying to use a continue statement outside of your while loop. The error is located in the catch block. If you look at the while block, you'll see that the it ends inside of the try block. The catch block is a new block of code and does not contain a while loop. Simply remove the continue statement from the catch block. Also, you can remove the line while(true) from the top of your code.

As a side note, here is a reply from Steven Parker to a similar question that outlines the exact requirements for that code challenge:

People often over-think this one and get too creative, and their answer is rejected for a variety of reasons (some which don't seem to make any sense).

Here are the secret "rules" you must follow for success on this one:

Your program must ask for and accept input ONE TIME ONLY If the input validates, your program will perform exactly as in Task 1 If the input does not validate, it will print the error message and exit Validation must be done by exception catching. There are other perfectly good methods that can be used for validation, but they will not pass this challenge