Throw Custom Error in JavaScript

- 1 minute read

JavaScript errors are thrown something goes wrong, halting code from executing.

The built in errors that are thrown by the language can provide useful information for debugging your code.

However, you sometimes might want to throw your own custom error. Here’s how you can go about doing this using the throw statement:

throw `Custom error!`;

And that’s all! Simply include an error message (which doesn’t have to be a string, by the way) just after the throw statement, and JavaScript will throw an error with that message.

One common use case is for preventing further code from executing after unexpected behavior that would not otherwise have thrown an error, such as when an error code is returned from an API request.

Link to this section Conclusion

By the way, you can use the throw statement inside try blocks.

I hope you found this useful! Happy error throwing!