liveBook · Manning

Throw

As explained in The Joy of JavaScript

A throw expression is an expression form that raises an exception from within an expression context.

A throw expression is an expression form that raises an exception from within an expression context. As a proposed JavaScript feature, it treats throwing more like a value-producing artifact than a statement restricted to a block. section 7.4.2 section 1.1

Its practical value is composability: code can raise an exception while initializing a parameter or evaluating a compact expression, without creating a separate function or block solely to contain throw. section 7.4.2

Default-parameter validation

function proofOfWork(block = throw new Error('Provide a non-null block object!')) { ... } section 7.4.2

The proposal extends throwing to expression-oriented locations such as:

  • Default-parameter initialization, as in proofOfWork. section 7.4.2
  • One-line arrow functions, conditionals, switch statements, and logical-operator evaluation. section 7.4.2

Without throw expressions, equivalent behavior requires wrapping the exception in a function or moving it into a block where throw is allowed. The feature therefore shortens error-handling code, but remains proposal-based and may require explicit enablement. section 7.4.2 section 1.1

How The Joy of JavaScript covers it

How deep it goes
Explains the proposal’s rationale and supported expression contexts, but defers detailed enablement instructions to an appendix.
Examples
Demonstrates a missing-block error through a proof-of-work function’s default parameter.
What it assumes
Assumes familiarity with JavaScript expressions, functions, default parameters, and conventional throw statements.
What you can do after
Evaluate how proposed throw expressions reduce wrapper functions and blocks when raising exceptions from expression contexts.
How it connects
Connects throw expressions with default parameters, arrow functions, conditionals, switch statements, logical operators, and exception handling.

Also explained in

Compare how 3 books explain throw →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.