How to Throw Error in JavaScript: Syntax and Examples
In JavaScript, you throw an error using the
throw statement followed by an Error object or any value. For example, throw new Error('message') stops execution and signals an error.Syntax
The throw statement is used to create a custom error. You write throw followed by an Error object or any value you want to signal as an error.
- throw: keyword to raise an error
- new Error('message'): creates an error object with a message
javascript
throw new Error('This is an error message');
Example
This example shows how to throw an error inside a function when a condition is not met. The error stops the program and shows the message.
javascript
function checkAge(age) { if (age < 18) { throw new Error('Age must be 18 or older'); } return 'Access granted'; } try { console.log(checkAge(16)); } catch (error) { console.log('Error caught:', error.message); }
Output
Error caught: Age must be 18 or older
Common Pitfalls
Common mistakes include throwing strings instead of Error objects, which makes debugging harder, and forgetting to catch errors, causing the program to crash.
javascript
/* Wrong way: throwing a string */ // throw 'This is an error'; /* Right way: throwing an Error object */ throw new Error('This is an error');
Quick Reference
| Action | Syntax Example |
|---|---|
| Throw a new error | throw new Error('message'); |
| Throw a custom error type | throw new TypeError('wrong type'); |
| Throw a string (not recommended) | throw 'error message'; |
| Catch an error | try { /* code */ } catch (e) { /* handle error */ } |
Key Takeaways
Use
throw new Error('message') to raise errors clearly.Always throw Error objects, not strings, for better debugging.
Use
try...catch blocks to handle thrown errors safely.Throwing an error stops normal code execution immediately.
Custom error types like
TypeError can clarify error causes.