What Can Be Thrown
You'll learn that JavaScript's throw statement can throw almost any value, but best practices strongly favor Error objects.
Throwing Anything
In JavaScript, the throw statement is surprisingly flexible—you can throw not just Error objects, but strings, numbers, booleans, or even objects. Technically, throw "oops" and throw 42 are both valid JavaScript.
throw "Something went wrong"; // Valid, but not recommended
throw 404; // Also valid, but problematic
throw { code: 'ERR_USER', msg: 'Invalid user' }; // Valid
throw new Error("Something went wrong"); // Recommended!
Why Error Objects Are Preferred
While you can throw primitive values, you should throw Error objects because:
- Stack traces:
Errorobjects automatically capture where the error occurred, making debugging far easier - Consistency: Standard error handling expects
Errorobjects withmessageandnameproperties - Type checking: You can use
instanceof Errorto distinguish errors from normal values
try {
throw new Error("File not found");
} catch (error) {
console.log(error.message); // "File not found"
console.log(error.stack); // Shows where the error originated
}
Think of it like sending a package: you could write an address on a banana and mail it, but using a proper envelope with tracking information is far more effective.
Key Takeaway: While JavaScript allows throwing any value, always throw Error objects (or their subclasses) to ensure proper stack traces, consistent handling, and easier debugging.