5

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?

brabec
  • 4,632
  • 8
  • 37
  • 63
  • 2
    Perhaps a [TypeError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FTypeError) or [RangeError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FRangeError) would be appropriate. Essentially you could just throw a normal [Error()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) with a custom message. – Lix Jan 09 '14 at 14:06
  • You can [throw](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw) an exception with whatever you want. – Matt Burland Jan 09 '14 at 14:07
  • 1
    Throw some type of `Error`, possibly [one that you have created yourself](http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript). – Jon Jan 09 '14 at 14:08

1 Answers1

3

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.

Community
  • 1
  • 1
Star Brilliant
  • 2,916
  • 24
  • 32