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 trialSean Lee
1,969 PointsI am having trouble using the try and catch method. Error: 'x' does not exist in the current context
Here is my code
try{ int x = int.Parse(Console.ReadLine()); } catch(FormatException){ }
using System;
namespace Treehouse.CodeChallenges
{
class Program
{
static void Main()
{
int a = 0;
Console.Write("Enter the number of times to print \"Yay!\": ");
try{
int x = int.Parse(Console.ReadLine());
}
catch(FormatException){
}
Console.WriteLine(x);
while (a < x)
{
Console.WriteLine("Yay!");
a++;
}
Console.ReadLine();
}
}
}
1 Answer
Balazs Peak
46,160 PointsThat is because the try's block has its own scope. If you declare a local variable there, that will be only accessible within that block and in its child blocks.
There are more than one solutions. You can pull out the x declaration, or you can take the while loop in, for example.