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

Having problems with a C# catch statement

Still having problems with my C# catch statement and it's driving me crazy. I've researched and tried so my things but it's still giving me errors starting at the catch line of code and also erroring below it.

Program.cs
using System;

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

2 Answers

Hi Rick,

It looks like you've nested your catch block inside the try block. The syntax should be:

try{ /*thing to try*/} catch(FormatException){/*other stuff*/ continue;}

Hope that helps, let me know if you have any other problems with this!

Evan nailed it. The try and catch need to be separate from each other.

steven simpson
steven simpson
11,644 Points

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

i believe it needs a variable like e