Let's say I have a function that accepts only non-negative numbers and I receive a negative argument.
In Python, I would raise a ValueError
. In Java, I would throw an IllegalArgumentException
. Is there any built-in exception I should throw in JavaScript, or should I return undefined
?
This is a common asked question: To throw an exception, or to return?
I suggest you see this: https://stackoverflow.com/a/1153149/2557927
If your method can't do what its name says it does, throw.
According to MDN, you probably wanted to throw RangeError("x should be a non-negative number");
. Although JavaScript does not limit the data type of what can be thrown, I think that throwing a Error
class is better than throwing a string since it is easier to be caught by uplevel functions.
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