Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 as NaN or undefined.

Use a throw statement 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. The Error function produces such an object with a given string describing the reason.

let reason = `Element ${elem} not found`
throw Error(reason)

When the throw statement executes, the function is terminated immediately. No return value is produced, not even undefined. Execution does not continue in the function call but instead in the nearest catch or finally clause, as described in the following sections.

  • + Share This
  • 🔖 Save To Your Account