我很难理解下面代码中三元运算的工作原理。
public static void main(String[] args) {
try{
throw new ArithmeticException("Exception Testing...");
}catch(Exception e){
msg = "First Statement : " + e.getCause() != null ? e.getMessage() : null; //Here e.getCause() is null
System.out.println(msg); // prints "Exception Testing..."
}
}
In the first Statement
block(Line 4), e.getcause()
为空,所以它应该打印First Statement: null
相反,它只打印Exception Testing...
.
我的问题是,
1)为什么 TRUE 块在三元运算符中执行而不是返回 null,而且,
2)Why First Statement:
不与消息一起打印Exception Testing...
?
提前致谢。
由于运算符优先级,+
之前应用过?:
,所以您要检查是否:
"First Statement : " + e.getCause()
为空 - 不是。
添加括号:
msg = "First Statement : " + (e.getCause() != null ? e.getMessage() : null);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)