throw
Throws an exception: stops the current code and passes the error to the nearest catch block.
Example
#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)
}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
#throw expression
throw new Error(message)
throw new Error(message, { cause })More examples
#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)
}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)
}try {
throw 'Something went wrong'
} catch (error) {
console.log(typeof error, error.message)
}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
asyncfunction,throwrejects the returned promise. Handle it withtry...catchplusawait, or with.catch(). - Don’t use exceptions for ordinary control flow, like exiting a loop. They’re meant for exceptional situations.
Related entries
#- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- classDefines a class: a template for creating objects that share the same fields and methods.
- Promise.prototype.catch()Registers an error-handling function that runs when the promise is rejected.
- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- ErrorThe built-in error object with a message and a stack trace. The basis for exceptions and custom error classes.
Spotted a mistake or missing an example? Write to us.