throw

Throws an exception: stops the current code and passes the error to the nearest catch block.

On this page

Example

#
JavaScript
function useFuel(fuel, amount) {
  if (amount > fuel) {
    throw new RangeError('Not enough fuel')
  }
  return fuel - amount
}

try {
  console.log(useFuel(10, 3))
  console.log(useFuel(10, 20))
} catch (error) {
  console.log(error.name, error.message)
}
Console
7
RangeError Not enough fuel

Definition and usage

#

The throw statement raises an error. The function stops running immediately, and the error travels up through the chain of calls until it reaches a catch block. If nothing catches it, it shows up in the console as an unhandled error.

You can throw any value, but always use Error objects or one of its variants, like TypeError and RangeError. They carry name and message fields, plus a stack trace (stack) that shows where the problem started.

For errors from your own domain, you can create a custom class that extends Error. The cause option lets you attach the original error when you wrap it in a more understandable message: new Error("Progress not saved", { cause: error }).

Syntax

#
Syntax
throw expression
throw new Error(message)
throw new Error(message, { cause })

More examples

#
A custom error class
JavaScript
class ValidationError extends Error {
  constructor(field, message) {
    super(message)
    this.name = 'ValidationError'
    this.field = field
  }
}

function validateEmail(email) {
  if (!email.includes('@')) {
    throw new ValidationError('email', 'Missing the @ character')
  }
  return true
}

try {
  validateEmail('emma.example.com')
} catch (error) {
  console.log(error instanceof ValidationError, error.field)
  console.log(error)
}
Console
true email
ValidationError: Missing the @ character
Wrapping an error with cause
JavaScript
function saveProgress(data) {
  try {
    JSON.parse(data)
  } catch (error) {
    throw new Error('Progress not saved', { cause: error })
  }
}

try {
  saveProgress('{broken')
} catch (error) {
  console.log(error.message)
  console.log(error.cause.name)
}
Console
Progress not saved
SyntaxError
Pitfall: throwing a string
JavaScript
try {
  throw 'Something went wrong'
} catch (error) {
  console.log(typeof error, error.message)
}
Console
string undefined

A thrown string has no message field and no stack trace. That’s why you should always throw Error objects.

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Throw an error as soon as you detect bad data, and write a message that says what to fix. “Points must be a number” helps more than “Error.”
  • Inside an async function, throw rejects the returned promise. Handle it with try...catch plus await, or with .catch().
  • Don’t use exceptions for ordinary control flow, like exiting a loop. They’re meant for exceptional situations.

Related entries

#

Spotted a mistake or missing an example? Write to us.