Check if null Boolean is true results in exception

后端 未结 7 1349
难免孤独
难免孤独 2020-11-28 05:20

I have the following code:

Boolean bool = null;

try 
{
    if (bool)
    {
        //DoSomething
    }                   
} 
catch (Exception e) 
{
    Syst         


        
相关标签:
7条回答
  • 2020-11-28 05:59

    Use the Apache BooleanUtils.

    (If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

    Don't reinvent the wheel. Leverage what's already been built and use isTrue():

    BooleanUtils.isTrue( bool );
    

    Checks if a Boolean value is true, handling null by returning false.

    If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

    0 讨论(0)
提交回复
热议问题