Check if null Boolean is true results in exception

后端 未结 7 1379
难免孤独
难免孤独 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:55

    When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.

    In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:

    if(bool != null && bool) { ... }
    

提交回复
热议问题