throw and Error Objects
throw interrupts normal execution with an exception. Error objects carry information about a failure, including a message.
Reject invalid input at the boundary rather than returning a plausible but incorrect result.
See the mechanism
-1invalidFollow one example
The valid call returns 4. The invalid call reaches throw, so no normal return follows it. The surrounding catch receives the Error and prints its message. Prefer an Error or a suitable subclass over throwing arbitrary strings so callers receive a consistent diagnostic object.
Predict, change and check
Predict: If another calculation followed throw inside the same branch, would it run?
Test your explanation: Place a console.log after throw and confirm it is not reached. Change the input to 0 and verify that the valid boundary returns normally.
The tasks below ask you to explain that result and apply the idea to different inputs.
Apply and distinguish
Throw something callers can interpret
JavaScript permits throwing values other than Error objects, but an Error normally supplies a useful name, message and stack context. Choose error categories that callers can interpret without parsing arbitrary display text. A failure should identify the violated contract, not silently replace bad data with a plausible result.
Validate at the boundary where an operation can meaningfully report the problem. Throwing inside a later timer callback is not caught by a try/catch that finished around the original registration call. Promise rejections also need their own async handling or an await within a relevant try block.
Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.