Step 1 of 5 · Reading · ~3 min
Learn
Error Handling
try / catch / throw
When something goes wrong, a function can stop normally returning and throw instead. The throw travels up through the callers until some try/catch stops it, or it ends the program. By the end of this lesson you can raise and catch errors, use finally for cleanup, decide which errors to handle and which to pass on, and know what try cannot catch.
Throwing
throw accepts any value, even throw 42 or throw "oops". Always throw an Error object (or a subclass): it carries a name, a message and a stack trace of where it happened, and String(err) gives "RangeError: port out of range: 70000". The built-in kinds you will meet:
TypeError: a value of the wrong type, such as callingnull.length.RangeError: a number outside its allowed range, such asnew Array(-1).ReferenceError: using a name that does not exist.SyntaxError: unparseable text, for example fromJSON.parse("{oops").
try, catch, finally
If anything in the try block throws, the rest of the block is skipped and control jumps to catch with the thrown value. finally runs always: after a normal finish, after a catch, and even when try or catch executes a return (the return value is held while finally runs). Use it for cleanup that must happen either way, such as releasing a lock or closing a file.
One trap: a return or throw inside finally replaces whatever was pending. try { throw new Error("lost") } finally { return "finally wins" } swallows the error.
Handle what you understand, rethrow the rest
A catch block catches everything, including bugs you did not expect. Inspect the error and only handle the cases you know:
Swallowing every error hides real bugs. Because throw can throw anything, code that must be safe against odd values checks first: err instanceof Error ? err.message : String(err).
What try/catch cannot catch
try only covers code that runs while the block is on the stack. A callback that runs later is outside it:
For promises, use .catch or await inside the try (the previous lessons).
Common mistakes
- Throwing strings or plain objects: no stack trace, no
name, anderr.messageisundefined. - An empty
catch {}that hides failures. - Catching an error just to log it and carrying on as if nothing happened.
- Wrapping a huge block in one
try, so you cannot tell which line failed. - Putting
returninfinally, which silently overrides a thrown error. - Expecting a
tryaroundsetTimeoutto catch what the callback throws.
Your exercise
Write the function that sits between code that throws and code that reports. The starter's execute throws several different kinds of values; you decide what to do with each, and count every attempt in finally.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…