Parsing date and time, try catch, variable for hours out of scope

I want to parse date and time. I want to catch if there is a format exception and I do the following:

    try
    {
        DateTime time = DateTime.Parse(Console.ReadLine());
    }
    catch (FormatException)
    {
        Console.WriteLine("Wrong date and time format!");
    }

However when I start working with the value 'time' C# says that "The name 'time' does not exist in the current context". Where is my mistake?

Jon Skeet
people
quotationmark

You've only declared time within the try block, so it's out of scope after that. You could declare it beforehand:

DateTime time;
try
{
    time = ...;
}
catch (FormatException)
{
    Console.WriteLine("Wrong date and time format!");
    return; // Or some other way of getting out of the method,
            // otherwise time won't be definitely assigned afterwards
}

However, it would be better to use DateTime.TryParse instead of catching the FormatException:

DateTime time;
if (DateTime.TryParse(Console.ReadLine(), out time)
{
    // Use time
}
else
{
    Console.WriteLine("Wrong date and time format!");
}

people

See more on this question at Stackoverflow