Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.3 — Throwing Your Own Errors
JavaScript · Example 4 of 4

Why you throw Error objects, not strings

throw new Error("message") stops a function and hands a problem to its caller; good errors use the right type, a message that says what was wrong and what was expected, your own Error subclasses for problems callers handle differently, and the ES2022 cause option to keep the original error.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write percent(part, whole) that throws a TypeError if either argument isn't a number, a RangeError if whole is 0, and otherwise returns the rounded percentage. Call it with (1, 4) and (1, 0) and print the results or the errors.

02

Make an OutOfStockError class with an item property and the name OutOfStockError. Throw it from buy(item, stock) when stock[item] is 0, catch it, and print Sorry, <item> is sold out.

Explain it without notes

01

Why should you always throw Error objects rather than strings?

02

How do you write a custom error class, and why would you?

03

What does the cause option do, and when do you use it?

04

What makes an error message helpful?

Why you throw Error objects, not strings

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

throwsString | type: string | instanceof Error: false | has a stack: false
throwsError | type: object | instanceof Error: true | has a stack: true