Since we can throw anything with the throw
keyword in Javascript, can't we just throw an error message string directly?
Does anyone know any catch in this?
Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw
. Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String.
You Can throw() Anything In JavaScript - And Other async/await Considerations.
An array of chars is often called a string when coding in C. C++ has proper string objects. An exception is thrown until some code catches it. If you do not write code to catch it, nothing will catch it and the program will terminate.
It's best to avoid throwing errors from inside a Promise, because they may not always be caught, depending on how the code that called them is structured. However it's good practice to return an error when rejecting a Promise, and you can return Error custom types just like any other Error.
While it is okay possible to throw any value, it is generally considered poor form to throw anything other than an instance of Error
or one of its subclasses. There are several reasons for this:
message
, stacktrace
, and name
properties that appear on Error
s.Yes, you can throw other values, but it's not a good practice.
Does anyone know any catch in this?
A string is not an error object, and does not convey any useful debugging information. Devtools rely on that, such as the file and line where the error was created, the stacktrace at the throw
location etc, which are available as properties on Error
objects.
Whenever you think of throwing a primitive string value, throw a new Error("<the string>")
instead.
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