21

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.

  • 5
    This is not possible with the ternary operator. You'll have to use `if` instead. – Jesper May 04 '15 at 17:29
  • I think it is supposed to be operations in all the three. throws is not an operation. – Sandeep Kaul May 04 '15 at 17:29
  • @ryekayo I have compile time error, `illegal start of expression` –  May 04 '15 at 17:29
  • Another dup: http://stackoverflow.com/q/19010399/1065197 – Luiggi Mendoza May 04 '15 at 17:33
  • 1
    For people falling in this question looking for a C++ answer. This is allowed in C++, either or both options in a ternary operator is allowed to `throw`. Maybe this is the origin of the confusion. https://stackoverflow.com/questions/7957696/throw-and-ternary-operator-in-c – alfC Dec 02 '20 at 19:30
  • You can if you want to abuse the language a little: `public static T throwException(RuntimeException e) { throw e; }` _pretends_ to return a value of the expected type, satisfying the compiler, but throws an exception instead. In use: `return (n < 0) ? throwException(new RuntimeException()) : list;` – Clement Cherlin Jul 19 '21 at 15:34

2 Answers2

31

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
6

It doesn't compile because what you want to do is not legal in Java. You can't return throw new RuntimeException(). Your return always have to return a value.

You have to use if instead of that.

Shondeslitch
  • 1,049
  • 1
  • 13
  • 26