How can you use `throw new Error()` to signal invalid input to a function?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can you use `throw new Error()` to signal invalid input to a function?
Asked by:
74 Viewed 74 Answers

Answer (74)

Best Answer
(376)
You can use `throw new Error()` within a function to indicate that the input provided is invalid. For example, if a function expects a number but receives a string, you can throw an error with a message explaining the expected input type: `throw new Error('Input must be a number.');` This helps the calling code understand why the function failed and take appropriate action.