在三元条件下抛出新的异常

5 java ternary-operator

我有这行代码:

List<Long> list = new ArrayList<>();

if (n < 0) throw new RuntimeException();

if (n == 0) return list;
Run Code Online (Sandbox Code Playgroud)

我想用Ternary condition:

return (n < 0) ? (throw new RuntimeException()) : list;
Run Code Online (Sandbox Code Playgroud)

但我有编译时异常.

Kay*_*man 6

你不能在三元条款中抛出异常.两个选项都必须返回一个throw new Exception();不满足的值.

解决方案,使用if.


Sho*_*tch 5

它无法编译,因为您想要做的在 Java 中是不合法的。你不能回来throw new RuntimeException()。你的回报总是必须返回一个值。

你必须使用 if 而不是那个。


归档时间:

查看次数:

3566 次

最近记录:

10 年,5 月 前