freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #36 of 61

errors · try · catch · finally

LambdaVSThe Mutator
Lambda saystry/catch/finally handles errors so one failure doesn’t crash everything.

Wrap risky code in try { … }; if it throws, catch (err) { … } runs with the error. finally { … } runs either way (cleanup). Catch only what you can handle — swallowing every error hides bugs. For async code, wrap await calls in try/catch the same way.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleParse possibly-invalid JSON inside try/catch and report success or the error.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>let msg; try{ JSON.parse('{bad json}'); msg='ok'; } catch(e){ msg='caught: '+e.message; }
document.getElementById('o').textContent=msg;</script></body></html>
▶ Open the interactive comic issue
‹ Json · Parse · Stringify · Replacer · ReviverErrors · Throwing · Custom Error Classes ›