Skip to content

operator "??" does not support throw expression - by design? #36014

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
ghost opened this issue Feb 24, 2019 · 3 comments
Closed

operator "??" does not support throw expression - by design? #36014

ghost opened this issue Feb 24, 2019 · 3 comments

Comments

@ghost
Copy link

ghost commented Feb 24, 2019

Expression x ?? expr, intuitively, should be equivalent to x != null ? x : expr, but it is not.

x != null ? x : throw "error"; // OK
x ?? throw "error"; // Error

Is it so by design?

@JxJPu9bD
Copy link

use '?:' instead?

@eernstg
Copy link
Member

eernstg commented Feb 25, 2019

That's a syntax error; just use x ?? (throw "error").

The underlying reason is that ?? requires an operand which is a <logicalOrExpression>, but <throwExpression> is derived directly from <expression> (so it's "more general" than <logicalOrExpression>).

@lrhn
Copy link
Member

lrhn commented Feb 25, 2019

The precedence of throw is such that this does not work. See also #24891.

The throw operator binds weakly. It means that throw foo + bar means throw (foo + bar) and not (throw foo) + bar, because the latter is meaningless anyway.
(In hindsight, that might not have been the best choice, because it prevents things like foo ?? throw bar, and you would not write throw foo + bar anyway, and it's confusing that it works differently from await).

As Erik has said, you have to wrap your throw in parentheses.

@ghost ghost closed this as completed Feb 25, 2019
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants