英文:
Is there a way to throw an exception in a return statement that uses the ternary operator?
问题
我有一个在某些情况下返回null的函数,例如:
public class Foo {
public static Double bar(double a, double b) {
if (a == 0 || b == 0) return null;
return a + b;
}
}
我想创建另一个函数,除了在满足条件时抛出错误,而不是返回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);
}
}
不幸的是,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 IllegalArgumentException();
return bar(a, b);
}
}
当然,这完全没问题,我只是想知道是否有一种方法可以在一行中实现这一点,或者将异常抛出集成到条件运算符中。非常感谢您的帮助。
英文:
I have a function that returns null in some cases, such as:
public Class Foo {
public static Double bar(double a, double b) {
if (a == 0 || b == 0) return null;
return a + b;
}
}
And I want to make another function that does exactly the same thing except it throws an error instead of returning null if that condition is met. I tried doing this:
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);
}
}
Unfortunately Java doesn't like this and gives me a syntax error on the "throw" token (and tells me it can't convert from IllegalArgumentException to Double). The only other way I can think to do this would be like this:
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);
}
}
Which is of course totally fine, I was just wondering if there was a way to do this in one line or integrate exception throwing into the conditional operator. Any help is greatly appreciated.
答案1
得分: 6
你可以使用Optional
来实现这个功能。
return Optional.ofNullable(bar(a, b))
.orElseThrow(() -> new IllegalArgumentException());
英文:
You can use Optional
for this
return Optional.ofNullable(bar(a, b))
.orElseThrow(() -> new IllegalArgumentException());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论