gpt4 book ai didi

java - 为什么我在使用三元运算符时不能抛出异常

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:43 24 4
gpt4 key购买 nike

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

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

最佳答案

你可以写一个实用方法

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");
}

关于java - 为什么我在使用三元运算符时不能抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13891841/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com