为什么我不能在使用三元运算符时引发异常

2022-09-03 17:23:20

这不会编译,并给出以下错误:。为什么?Illegal start of expression

public static AppConfig getInstance() {
    return mConfig != null ? mConfig : (throw new RuntimeException("error"));
}

答案 1

您可以编写一个实用程序方法

public class Util
{
  /** Always throws {@link RuntimeException} with the given message */
  public static <T> T throwException(String msg)
  {
      throw new RuntimeException(msg);
  }
}

并像这样使用它:

public static AppConfig getInstance() 
{
    return mConfig != null ? mConfig : Util.<AppConfig> throwException("error");
}

答案 2

这是因为 java 中的三元运算符采用 的形式,并且您给出一个语句作为最后一部分。这没有意义,因为语句不给出值,而表达式则提供值。当Java发现条件为假并试图给出第二个值时,它打算做什么?没有价值。expression ? expression : expression

三元运算符旨在允许您在两个变量之间快速进行选择,而无需使用完整语句 - 这不是您要尝试执行的操作,因此不要使用它,最佳解决方案很简单:if

public static AppConfig getInstance() {
    if (mConfig != null) {
        return mConfig;
    } else {
        throw new RuntimeException("error");
    }
}

三元运算符并不是为了产生副作用而设计的 - 虽然它可以产生副作用,但阅读它的人不会期望这一点,所以使用一个真正的陈述来说明它要好得多。if


推荐