[ACCEPTED]-C# Catch bool exception when using return-try-catch
How about using Boolean.TryParse instead?
bool result = false;
Boolean.TryParse( boolUpdate, out result );
return !result;
0
First, the general case: Just because you 5 return out of a block doesn't mean you can't 4 put it inside of a try/catch:
try
{
if ( whatever )
return true;
}
catch ( Exception E )
{
HandleMyException( E );
return false;
}
... this is 3 perfectly legal. Meanwhile, as other posters 2 have written, TryParse()
is probably what you want 1 in this specific case.
The following will return true only when 1 the string is 'true' and not generate exceptions.
bool value;
return bool.TryParse(boolUpdate, out value) && value;
When boolUpdate does not contain TRUE or 10 FALSE, you should catch the exception offcourse, but 9 what would you like to do when such a situation 8 arises ? You do not wan't to ignore the 7 exception, don't you, since I feel that 6 you want to return from the method anyway 5 ?
Instead of using Boolean.Parse
, you can use Boolean.TryParse
, wich will 4 return false if the Parse operation failed 3 (the boolUpdate argument in your case doesn't 2 contain true or false, for instance).
Or, you 1 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 5 does not throw, will put the parsed value 4 in the out parameter if the parsing was 3 successful, otherwise it will have the default 2 value, also will return true if the parsing 1 was successful.
string blah = "true";
bool val;
Boolean.TryParse( blah, out val);
return val;
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.