I'm using the code below and occasionally boolUpdate is not TRUE or FALSE and I get an exception, I can't surround this with a TRY CATCH block as it is using 'return', how can I catch this correctly?
if (!Boolean.Parse(boolUpdate)) return true;
I'm using the code below and occasionally boolUpdate is not TRUE or FALSE and I get an exception, I can't surround this with a TRY CATCH block as it is using 'return', how can I catch this correctly?
if (!Boolean.Parse(boolUpdate)) return true;
How about using Boolean.TryParse instead?
bool result = false;
Boolean.TryParse( boolUpdate, out result );
return !result;
First, the general case: Just because you return out of a block doesn't mean you can't put it inside of a try/catch:
try
{
if ( whatever )
return true;
}
catch ( Exception E )
{
HandleMyException( E );
return false;
}
... this is perfectly legal. Meanwhile, as other posters have written, TryParse()
is probably what you want in this specific case.
The following will return true only when the string is 'true' and not generate exceptions.
bool value;
return bool.TryParse(boolUpdate, out value) && value;
When boolUpdate does not contain TRUE or FALSE, you should catch the exception offcourse, but what would you like to do when such a situation arises ? You do not wan't to ignore the exception, don't you, since I feel that you want to return from the method anyway ?
Instead of using Boolean.Parse
, you can use Boolean.TryParse
, wich will return false if the Parse operation failed (the boolUpdate argument in your case doesn't contain true or false, for instance).
Or, you can do this:
try
{
return Boolean.Parse (boolUpdate)
}
catch(FormatException ex )
{
return false;
}
But, I would prefer to use TryParse:
bool result;
bool containsBool = Boolean.TryParse (boolUpdate, out result);
return containsBool && result;
You can try to use Boolean.TryParse...it does not throw, will put the parsed value in the out parameter if the parsing was successful, otherwise it will have the default value, also will return true if the parsing was successful.
string blah = "true";
bool val;
Boolean.TryParse( blah, out val);
return val;