C # Catch bool exception when using return

I use the code below and sometimes boolUpdate is not TRUE or FALSE and I get an exception, I cannot surround this with a TRY CATCH block as it uses 'return', how can I catch it correctly?

if (!Boolean.Parse(boolUpdate)) return true;

      

+2


source to share


5 answers


How about using Boolean.TryParse instead?



bool result = false;
Boolean.TryParse( boolUpdate, out result );
return !result;

      

+20


source


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.

+9


source


The following returns true only when the string is "true" and does not throw an exception.

        bool value;
        return bool.TryParse(boolUpdate, out value) && value;

      

+6


source


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;

      

+4


source


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;

      

0


source







All Articles