问题描述
我有以下代码:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
为什么我检查布尔变量bool会导致异常?
当它看到它不是真的时,它不应该跳过if语句吗?
当我删除if语句或检查它是否为null时,异常消失。
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.
推荐答案
当你有一个 boolean
时,它可以是 true
或 false
。然而,当你有一个 Boolean
时,它可以是 Boolean.TRUE
, Boolean.FALSE
或 null
与任何其他对象一样。
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.
在您的特定情况下,您的 Boolean
是 null
, if
语句触发隐式转换为 boolean
产生 NullPointerException
。您可能需要:
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) { ... }
这篇关于检查null Boolean是否为true导致异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!