In JS you can throw new Error()
, throw 'foo'
or even throw null
.
Why would you want to throw a non-Error
instance? I don't mean objects that inherit from Error
--I mean other random objects or primitives.
throw
just throws an arbitrary expression. It is not connected to the Error
object in any way; you can throw
any expression.
But it's probably a better idea to inherit from the Error object, which is exactly what the other standard built-in errors do:
EvalError
Creates an instance representing an error that occurs regarding the global function eval().
InternalError Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError
Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError
Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError
Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
All of these objects prototypically inherit from the Error object, so while it's legal to throw any arbitrary object, it probably makes more sense to throw the Error object or an object that inherits from Error, just like Javascript itself does.
There are several examples of the proper way to do this at this MDN page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With