Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is throw an expression?

Tags:

c++

The following post discusses the type of a throw expression: In C++, if throw is an expression, what is its type?. I would like to clarify a more basic thing: why should throw be an expression and not a (non-expression) statement just like return in the first place? I mean, would anyone want to write something like auto x = throw std::runtime_error("Error message")?

like image 359
AlwaysLearning Avatar asked Jul 03 '15 07:07

AlwaysLearning


1 Answers

If throw were a statement you couldn't use it with the conditional operator.

return success()
    ? computation()
    : throw std::runtime_error("oops");

Note : this may or may not have uses outside code obfuscation.

Edit : one useful case is inside C++11's strict constexpr functions which can only contain one instruction. Thanks @dyp for the insight !

like image 149
Quentin Avatar answered Sep 22 '22 18:09

Quentin