三元运算行为异常

ternary operation behaves weirdly

我很难理解下面代码中三元运算的工作原理。

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..."
         }
    }

first Statementblock(Line 4), e.getcause() 为空,因此它应该打印 First Statement: null 而不是只打印 Exception Testing....

我的问题是,

1)为什么在三元运算中执行了 TRUE 块而不是返回 null 并且

2)为什么 First Statement: 没有和 msg Exception Testing... 一起打印?

提前致谢。

由于运算符优先级,+?: 之前应用,因此您正在检查是否:

"First Statement : " + e.getCause()

为空 - 不是。

添加括号:

 msg = "First Statement : " + (e.getCause() != null ? e.getMessage() : null);