Skip to the workspace
Pebellslearn by building
Control Flow  ›  Lesson

throw and Error Objects

throw statement 12 min

javascript / throw and Error Objects

Explore each scene at your own pace.

01 · throw and Error Objects

throw and Error Objects

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

Walk through the modelthrow and Error ObjectsAuthored snapshots of the example; use Run below to test the code.
value-1
conditioninvalid
The boundary rule rejects negative reading time.
1 of 3

Follow one example

javascript

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.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.