In JavaScript, throwing literals (primitive values like strings, numbers, booleans, etc.) as exceptions is generally discouraged. While it is
syntactically valid to throw literals, it is considered a best practice to throw instances of the Error
class or its subclasses
instead.
Throwing an instance of the Error
class allows you to provide more meaningful information about the error.
The Error
class and its subclasses provide properties like message
and stack
that can be used to convey
useful details about the error, such as a description of the problem, the context in which it occurred, or a stack trace for debugging.
throw 404; // Noncompliant
throw "Invalid negative index."; // Noncompliant
Throwing literals can make it harder to handle and differentiate between different types of errors. Instead, you should use one of the exception
types specifically created for the purpose or define your own subclass of the Error
class.
throw new Error("Status: " + 404);
throw new RangeError("Invalid negative index.");