Skip to the workspace
Pebellslearn by building
Control Flow  ›  Lesson

try / catch / finally

Exceptional Handling 12 min

javascript / try / catch / finally

Explore each scene at your own pace.

01 · try / catch / finally

try / catch / finally

try / catch / finally

try runs code that may throw; catch handles an exception; finally runs when control leaves the try/catch construct, including after a return or throw.

Recovery and cleanup are separate responsibilities.

See the mechanism

Walk through the modeltry / catch / finallyAuthored snapshots of the example; use Run below to test the code.
events["try"]
The protected work begins.
1 of 3

Follow one example

javascript

The throw skips the remaining try body and enters catch. finally then records cleanup. If no error occurs, catch is skipped but finally still runs when the construct is left. Do not return from finally casually: it can override an earlier return or exception. Catch only errors you can meaningfully handle, and preserve useful diagnostics.

Predict, change and check

Predict: If throw is removed, which two event labels remain?

Test your explanation: Test both paths. Add a statement after the construct to see that handled errors allow execution to continue.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Recovery must preserve useful evidence

catch handles a thrown completion from its protected execution, including a rejected promise that is awaited there. A caught error is not automatically repaired: return a documented fallback, retry under a bounded policy, or rethrow when this layer cannot handle it.

finally is for work that must run while the operation leaves the protected region. A return or throw inside finally can override an earlier return or throw and obscure the original outcome. Keep cleanup small and test success, expected failure and cleanup failure separately.

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.