Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling TimeSpan Exception in c#

I have these below lines of code.

if (TimeSpan.ParseExact((VSFlexShift.get_TextMatrix(VSFlexShift.Row, 2)), @"hh\:mm\:ss", CultureInfo.InvariantCulture) > TimeSpan.MaxValue)

which i wrote to check if the end user types the time as 12:68:56 Some what like this it should return;. But what is happening right now is the code directly catch the Exception. Is there any way so that i can handle it inside the loop only rather than its going to Catch(Exception ex).

Exception Message:

The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits.

like image 923
Shreyas Achar Avatar asked Aug 30 '25 18:08

Shreyas Achar


1 Answers

You're looking for the equivalent TimeSpan.TryParseExact which returns a bool instead of throwing an exception:

TimeSpan timeSpan;
if (!TimeSpan.TryParseExact(VSFlexShift.get_TextMatrix(VSFlexShift.Row, 2),
    @"hh\:mm\:ss", CultureInfo.InvariantCulture, out timeSpan))
{
    // TimeSpan isn't valid.
}

Regarding the > TimeSpan.MaxValue, I'm not really sure why what you're trying to check, but a TimeSpan object can't be larger then it's own maximum value.

like image 138
Yuval Itzchakov Avatar answered Sep 02 '25 17:09

Yuval Itzchakov