Question
How can you use `throw new Error()` to signal invalid input to a function?
Asked by: USER6222
74 Viewed
74 Answers
Answer (74)
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.