Error Handling
Things go wrong: bad input, network failures, missing data. Error handling lets your program recover gracefully instead of crashing.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Syntax
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 27, 2026
Related tutorials
Learning objectives#
- Catch errors with try…catch
- Run cleanup code in finally
- Throw meaningful errors
- Use the right built-in error types
Explanation#
Code inside try runs normally. If anything throws, execution jumps to catch, which receives the error object.
finally runs whether there was an error or not — useful for cleanup such as hiding a loading spinner.
throw new Error('message') creates your own error. Use specific types: TypeError for wrong types, RangeError for out-of-range values.
Every error has name and message properties (and a stack trace for debugging).
Syntax#
try {
riskyCode();
} catch (err) {
console.log(err.name, err.message);
} finally {
cleanup();
}
Code example: Validating ages safely#
function parseAge(text) {
const age = Number(text);
if (Number.isNaN(age)) throw new TypeError(`"${text}" is not a number`);
if (age < 0) throw new RangeError('Age cannot be negative');
return age;
}
for (const input of ['25', 'abc', '-3']) {
try {
console.log('Age:', parseAge(input));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
} finally {
console.log('checked', input);
}
}
Age: 25 checked 25 TypeError: "abc" is not a number checked abc RangeError: Age cannot be negative checked -3
Step-by-step explanation#
- parseAge throws a TypeError or RangeError for bad input.
- For "25" no error occurs, so catch is skipped.
- For "abc" the TypeError is caught and its name and message printed.
- finally runs every time, error or not.
Real-world use case#
Showing “Could not load products — try again” instead of a blank page when an API call fails.
Common mistakes#
catch (e) {} hides problems. At least log the error or show a message.
throw 'oops' has no name or stack trace. Throw Error objects.
Best practices#
- Catch errors where you can do something useful
- Throw Error objects with clear messages
- Use finally for cleanup
- Log unexpected errors for debugging
Remember this#
try = attempt, catch = rescue, finally = always tidy up.
throw new Error(…), never throw a plain string.
Every error has a name and a message.
Practice exercise#
Your task: Write safeDivide(a, b) that throws a RangeError when b is 0, and call it inside try…catch.
Show solution
function safeDivide(a, b) {
if (b === 0) throw new RangeError('Cannot divide by zero');
return a / b;
}
try { console.log(safeDivide(10, 0)); } catch (e) { console.log(e.message); }
Mini quiz#
finally runs only when an error occurred.
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.