I have the following code:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Why does my check up on the Boolean variable "bool" result in an exception?
Shouldn't it just jump right past the if statement when it "sees" that it isn't true?
When I remove the if statement or check up on if it's NOT null, the exception goes away.
解决方案
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) { ... }