Skip to content
engineering workbench.by StudyPort Academy
Learning path
Foundations15 minLESSON 10 / 34

Basic error handling with try/catch

01

Understand the idea

One malformed saved preference stops the page from rendering. A recoverable input problem escaped the code that knew how to handle it.

A checkpoint for failure

Stored data can be damaged, a request can fail, and an input can be invalid. Without a recovery decision, one failure may stop the rest of an interaction. Error handling is how you choose what the person sees and what information the developer keeps.

What throwing changes

An error carries a message and usually a stack trace. You can throw your own error when an input violates a requirement. Throwing is useful when returning an ordinary value would let later code mistake failure for success.

Throwing is different from returning an ordinary value. A thrown error leaves the current path and looks for a matching catch. The statements after the failing line inside try are skipped. Work already completed is not automatically undone, so try/catch is not a transaction or an undo button.

The parts of a recovery path
PartJobA useful question
trySurround work that may throwWhich operation can fail?
catchHandle the thrown valueCan this code recover meaningfully?
finallyRun cleanup after try/catchWhat resource must be released either way?
throw new Error(...)Report that the current work cannot finishWhat message helps the caller decide?
await inside tryLet a rejected awaited promise reach catchDid I actually wait for the failing operation?

Catch a failure you can handle

Put only the work you can meaningfully recover from inside the try. The catch might show a useful message, use a safe default, or add context and rethrow. An empty catch hides the evidence while leaving the program in an uncertain state.

Cleanup and async boundaries

A finally block runs when control leaves the try/catch, even after a return or throw. Use it for cleanup such as clearing a busy state. Avoid returning from finally because it can override the result or error you were trying to preserve.

Make recovery visible

A surrounding try does not catch an error thrown later in a timer callback. Likewise, a rejection needs a rejection handler or an awaited promise inside the try. The checkpoint must cover the actual execution that can fail, not just the line that schedules it.

In this example, zero is an explicit fallback for an unreadable saved count. That would be a poor fallback for a failed payment total, where pretending the amount is zero could hide a serious mistake. Pick a recovery that fits the task. A warning explains that recovery happened, rather than making the failure disappear.

02

Mental model

FOLLOW THE VALUE

JSON text
try parse
object

The normal path returns the saved count.

01 / 03Trace the transformation

03

Live example

The valid input returns 3. Change the string to invalid and the catch will report the failure and return the chosen fallback, zero.

Opening editor…
LIVE PREVIEW
Console 0

Your console output appears here.

Saved on this deviceJavaScript · ES2022
04

Guided challenge

Parse before reading

Turn the input text into a value before reading count. Keep the recovery path available for malformed JSON.

Opening editor…
LIVE PREVIEW
Console 0

Your console output appears here.

Saved on this deviceJavaScript · ES2022

EXPECTED CONSOLE OUTPUT

3

Hints 0/2

    Use all hints or make 3 failed runs (0/3).

    05

    Free sandbox

    Make a variation, test an assumption, or break the example on purpose. This draft is saved separately.

    Opening editor…
    LIVE PREVIEW
    Console 0

    Your console output appears here.

    Saved on this deviceJavaScript · ES2022
    06

    Quiz

    A quick check for understanding. Retry as often as you like; your learning path stays open.

    01After a statement throws inside try, what runs next?
    02What is finally best used for?

    Ready to call this one understood?

    Mark this lesson complete to earn 100 XP. You can always revisit it.

    Sign in to save progress
    Next lesson