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

Thomas Strickland
Thomas Strickland
1,062 Points

How do I set up Try-Catch to throw a Format Exception?

Trying to set up a Try-Catch to throw a Format Exception and I'm failing miserably. Just trying to verify the user can only use whole numbers and if not then displays an error message. If someone can at least point me in the right direction or explain what I'm doing wrong, I'd be very appreciative.

Program.cs
using System;

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

            var x = Convert.ToInt32(Console.ReadLine());

            try
            {
                var times = int.Parse(x);
            }
            catch(FormatException)
            {
                Console.WriteLine("You must enter a whole number.");
            }

            for (;x >= 1; x--)
            {
                Console.WriteLine("Yay");
            }   

        }
    }
}

1 Answer

Steven Parker
Steven Parker
231,248 Points

You're actually pretty close. Here's some hints:

  • you convert your string into a number before the try, but it should be done inside.
  • int.Parse is for converting strings, but x is already a number
  • times is assigned but never used (but you don't need it anyway)
  • FYI: given a string, Convert.ToInt32 does the same thing as int.Parse
Thomas Strickland
Thomas Strickland
1,062 Points

Thank you so much, I missed the part of the vid that said put the code you want to try "IN" the try brackets lol.