三元运算行为异常 [英] ternary operation behaves weirdly
本文介绍了三元运算行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,我很难理解三元运算的工作原理。
I have a difficulty in understanding how the ternary operation works in the below code.
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..."
}
}
第一条语句
块(第4行),e.getcause()
为空,因此应打印第一个语句:空
而是仅打印异常测试...
。
In the first Statement
block(Line 4), e.getcause()
is null so it should print First Statement: null
instead it prints only Exception Testing...
.
我的问题是,
1)为什么在三元运算中执行了TRUE块而不是返回null,
1)Why TRUE block got executed in the ternary operation instead of returning null and also,
2)为什么第一条语句:
没有与msg Exception Testing ...
一起输出?
2)Why First Statement:
is not printed with the msg Exception Testing...
?
预先表示感谢。
推荐答案
由于运算符优先级, +
在 ??:
之前应用,因此您正在检查是否:
Because of operator precedence, +
is applied before ?:
, so you are checking whether:
"First Statement : " + e.getCause()
是null-不是。
添加括号:
msg = "First Statement : " + (e.getCause() != null ? e.getMessage() : null);
这篇关于三元运算行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文