有没有办法在使用三元运算符的 return 语句中抛出异常?

Nic*_*ick 0 java return conditional-operator

我有一个在某些情况下返回 null 的函数,例如:

public Class Foo {
    public static Double bar(double a, double b) {
        if (a == 0 || b == 0) return null;
        return a + b;
    }
}
Run Code Online (Sandbox Code Playgroud)

而且我想创建另一个函数,它执行完全相同的操作,只是在满足该条件时抛出错误而不是返回 null。我尝试这样做:

public Class Foo {

    public static Double bar(double a, double b) {
        if (a == 0 || b == 0) return null;
        return a + b;
    }

    public static Double barWithException(double a, double b) {
        return bar(a, b) == null ? throw new IllegalArgumentException() : bar(a, b);
    }

}
Run Code Online (Sandbox Code Playgroud)

不幸的是,Java 不喜欢这样,并且在“throw”标记上给了我一个语法错误(并告诉我它不能从 IllegalArgumentException 转换为 Double)。我能想到的唯一另一种方法是这样的:

public Class Foo {
    
        public static Double bar(double a, double b) {
            if (a == 0 || b == 0) return null;
            return a + b;
        }
    
        public static Double barWithException(double a, double b) {
            if (bar(a, b) == null) throw new IllegalArugmentException();
            return bar(a, b);
        }
    
    }
Run Code Online (Sandbox Code Playgroud)

这当然完全没问题,我只是想知道是否有办法在一行中执行此操作或将异常抛出集成到条件运算符中。任何帮助是极大的赞赏。

Ekl*_*vya 5

你可以用Optional这个

return Optional.ofNullable(bar(a, b))
        .orElseThrow(() -> new IllegalArgumentException());
Run Code Online (Sandbox Code Playgroud)