Throwing an Error and Testing It

Learn how to test when an error is expected.

Good programming practice must pro-actively consider bad function inputs and handle them within the function.

Throwing an error

We’ve thought briefly about strings, negative numbers, and fractions as inputs into getCollatzSequence. What about array inputs or objects? The easiest solution is to throw an error if the input is not a positive whole number. We’ve chosen to use a TypeError. A more informative error scheme would be to give a RangeError if the input is a number but not a positive integer, and only use TypeError for non-number inputs.

Get hands-on with 1200+ tech skills courses.