【问题标题】:Why can't I throw an exception while using the ternary operator为什么我在使用三元运算符时不能抛出异常
【发布时间】:2012-12-15 11:40:16
【问题描述】:

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

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

【问题讨论】:

  • 因为throw 不是表达式
  • "return (throw new RuntimeException("error"));" - 你不能返回一个 throw new exception()
  • 空对象模式在这里值得一提。

标签: java android


【解决方案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");
}

【讨论】:

  • 为什么不将throwException 声明为返回Object
  • @Navin 对象需要对调用者进行强制转换。 T 不需要强制转换(至少有时......取决于编译器)。在 Java 8 中,甚至不需要 &lt;AppConfig&gt;(编译器可以弄清楚)
  • 啊好的,很方便:)
  • 什么是 Util 类?
  • @jonsinfinity Util 是定义 throwException 的类。为了清楚起见,我更新了我的答案
【解决方案2】:

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

三元运算符旨在让您在不​​使用完整的if 语句的情况下快速在两个变量之间做出选择 - 这不是您想要做的,所以不要使用它,最好的解决方案是简单地说:

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

三元运算符不是为了产生副作用而设计的——虽然它可以产生副作用,但阅读它的人不会想到,所以最好使用真正的if 语句来说明清楚。

【讨论】:

    【解决方案3】:

    如果它对某人有帮助,这是使用 java 8+ 可选的答案:

    public static AppConfig getInstance() {
        return Optional.ofNullable(mConfig).orElseThrow(() -> new RuntimeException("error"));
    }
    

    【讨论】:

      【解决方案4】:

      您正在尝试返回throw new RuntimeException("error")。这就是您收到错误的原因。因为在true 情况下,您将返回AppConfig,而在false 情况下,您将返回exception

      【讨论】:

        猜你喜欢
        • 2016-01-08
        • 1970-01-01
        • 2014-11-29
        • 2015-10-07
        • 2016-05-15
        • 2016-03-04
        • 2013-07-30
        • 1970-01-01
        • 2015-07-16
        相关资源
        最近更新 更多