Throw new exception in ternary state

I have the following 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 a compile time exception.

+3


source to share


2 answers


You cannot throw a triple clause exception. Both parameters must return a value that is throw new Exception();

not satisfying.



Solution, use if

.

+3


source


It doesn't compile because what you want to do is not legal in Java. You cannot return throw new RuntimeException()

. Your return should always return a value.



You should use if instead.

+2


source







All Articles