这不会编译并出现以下错误:Illegal start of expression
。为什么?为什么我在使用三元运算符时不能抛出异常
public static AppConfig getInstance() {
return mConfig != null ? mConfig : (throw new RuntimeException("error"));
}
这不会编译并出现以下错误:Illegal start of expression
。为什么?为什么我在使用三元运算符时不能抛出异常
public static AppConfig getInstance() {
return mConfig != null ? mConfig : (throw new RuntimeException("error"));
}
这是因为java中的三元运算符采用expression ? expression : expression
的形式,并且您将声明作为最后一部分。这是没有意义的,因为一个声明没有给出一个值,而表达式。当Java发现条件是错误的并试图给出第二个值时,Java意味着要做什么?没有价值。
三元运算符旨在允许您快速在两个变量之间进行选择,而无需使用完整的if
语句 - 这不是您正在尝试执行的操作,所以不要使用它,最好的解决方案就是:
public static AppConfig getInstance() {
if (mConfig != null) {
return mConfig;
} else {
throw new RuntimeException("error");
}
}
三元运算符的目的不是产生副作用 - 虽然它可以做成能产生他们,读书人也不会想到的是,所以它的更好使用真实if
语句,以它清楚。
您正在尝试返回throw new RuntimeException("error")
。这就是你错误的原因。因为在true
的情况下您要退回AppConfig
,并且在false
的情况下您要退回exception
。
您可以编写一个实用方法
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");
}
因为'throw'不是表达式 –
“返回(抛出新的RuntimeException(” 错误“)) ;” - 你不能返回抛出新的异常() –
空值对象模式在这里值得一提。 –