Lesson 27 of 34 · Classes & Errors
JavaScript Error Handling: try, catch and Custom Errors
Things go wrong. Users type letters where numbers belong, files are missing, servers go down and JSON arrives broken. Professional code doesn't pretend errors never happen. It expects them, handles them where it makes sense and reports them clearly everywhere else.
In this lesson you'll learn how JavaScript errors work, how to catch them, how to throw your own, and how to create custom error types that make bugs easy to diagnose.
What an error looks like
When something goes wrong at runtime, JavaScript throws an error object. If nothing catches it, the program stops:
const hero = null;
console.log(hero.name); // TypeError: Cannot read properties of null (reading 'name')
Every error has a name (the kind of error) and a message (what happened). You've already met a few built-in kinds:
ReferenceError: using a variable that doesn't exist.TypeError: using a value the wrong way, like calling something that isn't a function.RangeError: a number outside the allowed range.SyntaxError: invalid code, or invalid JSON passed toJSON.parse.
try and catch
Code that might fail goes in a try block. If an error is thrown inside it, JavaScript jumps straight to the catch block, where you receive the error object:
try {
const data = JSON.parse("{ broken json");
console.log(data);
} catch (error) {
console.log(error.name); // SyntaxError
console.log("Could not load the save file.");
}
console.log("The program keeps running!");
If you don't need the error object, you can leave out the parentheses: catch { ... }.
finally
A finally block runs no matter what: after try succeeds, after catch handles an error, even after a return. It's the place for cleanup like closing connections or hiding a loading spinner:
try {
console.log("Loading...");
} finally {
console.log("Done loading."); // always runs
}
Throwing your own errors
Use throw to signal that something is wrong. Always throw an Error object (or a subclass), never a plain string, because Error objects carry a name, a message and a stack trace:
function setVolume(level) {
if (level < 0 || level > 10) {
throw new RangeError(`Volume must be 0-10, got ${level}`);
}
return level;
}
Throw when your function can't do its job. The caller then decides how to recover.
Custom error classes
For errors that are specific to your program, extend Error. Custom errors can carry extra data, and callers can recognise them with instanceof:
class QuestError extends Error {
constructor(message, questId) {
super(message); // sets this.message
this.name = "QuestError";
this.questId = questId;
}
}
try {
throw new QuestError("The dragon is asleep", 42);
} catch (error) {
if (error instanceof QuestError) {
console.log(`Quest ${error.questId} failed: ${error.message}`);
} else {
throw error; // not ours: let someone else deal with it
}
}
Notice the else { throw error; }. Catch the errors you know how to handle, and rethrow the rest. Silently swallowing unknown errors hides real bugs.
Common mistakes
- Empty catch blocks.
catch {}with nothing inside makes bugs invisible. At least log the error, or rethrow it. - Throwing strings.
throw "oops"has no name or stack trace. Usethrow new Error("oops"). - Wrapping everything in try/catch. Only catch where you can actually do something useful.
- Forgetting
this.namein a custom error. Without it, your error is reported as a plainError.
Assignment
- Complete the class
InsufficientGoldError, which extendsError. Its constructor takes(needed, available), and the error must have:message:"Need <needed> gold, but only have <available>"name:"InsufficientGoldError"- properties
neededandavailable
- Write
buyItem(gold, price), which returns the gold left after buying:- If
priceis zero or negative, throw aRangeErrorwith the message"Price must be positive". - If
priceis more thangold, throw anInsufficientGoldError. - Otherwise return
gold - price.
- If
- Write
safeParse(json, fallback), which returnsJSON.parse(json), orfallbackif the text isn't valid JSON.fallbackdefaults tonull.
buyItem(100, 30); // 70
buyItem(20, 50); // throws InsufficientGoldError: Need 50 gold, but only have 20
safeParse('{"a":1}'); // { a: 1 }
safeParse("oops"); // nullPremium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Errors and exceptions in other languages
- Python Exceptions: try, except, else and finally · Python
- Go Error Handling: error Values and if err != nil · Go
- Java Exceptions: try, catch, finally and Custom Exceptions · Java
- C# Exceptions: try, catch, finally and Custom Exceptions · C#
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .