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

Throw new exception in Ternary condition

我有这行代码:

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

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

if (n == 0) return list;

我想使用 Ternary condition :

return (n < 0) ? (throw new RuntimeException()) : list;

但是我有编译时异常。

不能在三元子句中抛出异常。两个选项都必须return一个值,throw new Exception();不满足。

解决方法,使用if.

它无法编译,因为你想做的事情在 Java 中是不合法的。 你不能 return throw new RuntimeException()。你的return总是要return一个值。

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