javaternary-operator

Throw new exception in Ternary condition


I have this lines of code:

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

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

if (n == 0) return list;

I want to use Ternary condition :

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

But i have compile time exception.


Solution

  • You can't throw an exception in a ternary clause. Both options must return a value, which throw new Exception(); doesn't satisfy.

    Solution, use if.