3

This compiles:

struct A{};
struct B{};

int main(){
  if(true)
    throw A();
  else
    throw B();  
}

, but

struct A{};
struct B{};

int main(){
  throw( true ?  A() : B() );
}

won't.

Can I throw with the ternary operator?

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142

3 Answers3

7

A and B are different, incompatible types, so the expression true ? A() : B() is ill-typed (it'd have to be either an A or a B).

Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
2

Ternary operator needs to have the same type(or something convertible to the same type) on both paths otherwise the compiler can't reason about type safety.

Sorin
  • 11,863
  • 22
  • 26
0

If there is a result from the conditional operator, the types needs to be somehow compatible. If the types are not compatible, you can still throw from a ternary operator, though:

condition? throw A(): throw B();

Although all compilers I tried do compile the above statement, it seems to be illegal: according to 5.16 [expr.cond] paragraph 2, first bullet "The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (15.1); ...". To counter that constraint it is possible to use something like

condition? (throw A()), true: throw B()
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380