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?
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!");
}
See more on this question at Stackoverflow