C # Catch bool exception when using return
How about using Boolean.TryParse instead?
bool result = false;
Boolean.TryParse( boolUpdate, out result );
return !result;
source to share
First, the general case: just because you're returning from a block doesn't mean you can't put it inside a try / catch:
try
{
if ( whatever )
return true;
}
catch ( Exception E )
{
HandleMyException( E );
return false;
}
... it is perfectly legal. Meanwhile, as other posters have written, it TryParse()
's probably what you want in this particular case.
source to share
If boolUpdate is not TRUE or FALSE, you should catch an offcourse exception, but what would you like to do when this happens? You don't want to ignore the exception, do you, because I feel like you want to return from the method anyway?
Instead of using, Boolean.Parse
you can use Boolean.TryParse
which will return false if the Parse operation fails (the boolUpdate argument in your case, for example, does not contain true or false).
Or you can do this:
try
{
return Boolean.Parse (boolUpdate)
}
catch(FormatException ex )
{
return false;
}
But I would rather use TryParse:
bool result;
bool containsBool = Boolean.TryParse (boolUpdate, out result);
return containsBool && result;
source to share
You can try to use Boolean.TryParse ... it doesn't throw, will put the parsed value in the out parameter if the parse was successful, otherwise it will have a default value, will also return true if the parse was successful.
string blah = "true";
bool val;
Boolean.TryParse( blah, out val);
return val;
source to share