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

blake Judson
blake Judson
4,921 Points

C# basics Final Step 2 I'm having some trouble understanding how the try catch method works.

Where do I place the catch in relation to the try? For some reason my code doesn't function as it did before when I try to add the try/catch.

Program.cs
using System;

namespace Treehouse.CodeChallenges
{
    class Program
    {
        static void Main()
        {
            while(true)
            {
            try
            {
            Console.Write("Enter the number of times to print \"Yay!\": ");
            var entry = Console.ReadLine();

            int intEntry = int.Parse(entry);
            for(int i = 0;i<intEntry;i++)
                {
                 Console.Write("Yay!");   
                }
            }
            catch(FormatException)
            {
                Console.Write("You must enter a whole number!");
                continue;
            }
            }


        }
    }
}

2 Answers

Jesper Henriksen
Jesper Henriksen
3,308 Points

The code you posted already contains the sufficient try/catch method. Basically you put code you want to "test" for errors inside the try{ } and then handle the different types of exceptions in the catch (exception type) On later stages in the C# courses you get to create your own exceptions (I can't remember if its in the c# basics or the next course on c# which I highly recommend)

The code you posted only handles formatting exceptions meaning that other kinds of errors would still crash the program.

blake Judson
blake Judson
4,921 Points

Thank you!

Well for some reason my code isn't passing the test. It says "step 1 is no longer passing" which was to simply print out "Yay!" a set number of times. Is there something wrong with the Treehouse tester or something?

Jesper Henriksen
Jesper Henriksen
3,308 Points

The only thing I would do different is to use the Console.WriteLine(); instead of just using Console.Write(); The difference is that WriteLine() creates a new line for repetition. I have not had bad experiences with the tester, I have however sometimes had some benefits from having a workspace with my code open so I can view it while doing the tests.