- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.15 Throwing Exceptions
If a function is unable to compute a result, it can throw an exception. Depending on the kind of failure, this can be a better strategy than returning an error value such asNaNorundefined.
Use athrowstatement to throw an exception:
throw value
The exception value can be a value of any type, but it is conventional to throw an error object. TheErrorfunction produces such an object with a given string describing the reason.
let reason = `Element ${elem} not found` throw Error(reason)
When thethrowstatement executes, the function is terminated immediately. No return value is produced, not evenundefined. Execution does not continue in the function call but instead in the nearestcatchorfinallyclause, as described in the following sections.