When JavaScript hits a problem, it throws an error that stops the script cold unless you handle it. This lesson covers wrapping risky code in try/catch, using finally for guaranteed cleanup, reading the error object's name and message, throwing your own custom errors with throw, and recognizing common error types like TypeError and ReferenceError.
1JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 1
Errors are not failures—they are feedback! Today we'll learn to handle them like pros so our apps never crash.
// The Art of Error HandlingError Handling
2JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 2
When JavaScript hits a problem (like a missing variable), it 'throws' an error and stops the script immediately.
console.log(user.name); // Uncaught ReferenceError: user is not defined
console.log('This will NEVER run.');The Crash
3JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 3
To prevent a crash, we wrap risky code in a 'try' block. If it fails, execution jumps safely to the 'catch' block.
try {
console.log(user.name);
} catch (error) {
console.log('Caught it! No crash.');
}Try / Catch
4JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 4
The 'error' object inside catch is useful! It has a 'name' (ReferenceError, TypeError, etc.) and a 'message'.
catch (error) {
console.log(error.name); // ReferenceError
console.log(error.message); // user is not defined
}The Error Object
5JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 5
The 'finally' block is a cleanup crew. It runs whether there was an error or not. Perfect for closing files or stopping loaders.
try {
fetchData();
} finally {
stopLoadingSpinner(); // ALWAYS runs
}Finally Block
6JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 6
You can create your own errors using 'throw'. This is great for data validation and enforcing business rules.
function setAge(age) {
if (age < 0) throw new Error('Age cannot be negative');
this.age = age;
}Custom Errors
7JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 7
There are many error types: TypeError (wrong type), SyntaxError (typo), and RangeError (value out of limits).
const pi = 3.14;
pi = 4; // TypeError: Assignment to constant variableError Types
8JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 8
Best Practice: Only catch errors you expect and can handle. Don't hide important bugs with empty catch blocks!
catch (e) {
// Bad practice: doing nothing
}Best Practices
9JS Error Handling | JavaScript Tutorial - In-Depth Guide Part 9
Resiliency Mastered! Your code is now robust, safe, and ready for production environments.
<h1>Code: Bulletproof</h1>Bulletproof
10Step-by-Step Breakdown
Errors are not failures—they are feedback! Today we'll learn to handle them like pros so our apps never crash.
When JavaScript hits a problem (like a missing variable), it 'throws' an error and stops the script immediately.
To prevent a crash, we wrap risky code in a 'try' block. If it fails, execution jumps safely to the 'catch' block.
Checkpoint: What happens to the code inside 'try' if an error occurs on the first line?
- →It continues the rest of the block
- →It immediately jumps to the catch block
The 'error' object inside catch is useful! It has a 'name' (ReferenceError, TypeError, etc.) and a 'message'.
The 'finally' block is a cleanup crew. It runs whether there was an error or not. Perfect for closing files or stopping loaders.
Checkpoint: If the try block finishes successfully, does the finally block still run?
- →No, only on error
- →Yes, it always runs
You can create your own errors using 'throw'. This is great for data validation and enforcing business rules.
There are many error types: TypeError (wrong type), SyntaxError (typo), and RangeError (value out of limits).
Best Practice: Only catch errors you expect and can handle. Don't hide important bugs with empty catch blocks!
Final Challenge: Which operator is used to manually trigger an error?
- →catch
- →throw
- →break
Resiliency Mastered! Your code is now robust, safe, and ready for production environments.
Level Up 🚀
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Move Focus to Validation Errors So Screen Reader Users Notice Them
When a caught validation error produces an inline message (e.g. 'Age cannot be negative'), simply displaying red text isn't enough — programmatically move focus to the error message (or the invalid field) and use role="alert" so assistive technology announces it immediately instead of the user having to discover it by chance.
errorEl.textContent = message; errorEl.setAttribute('role', 'alert'); field.focus();SEO Implications
- 1
Unhandled Errors Can Crash Client-Side Rendering and Leave Pages Blank for Crawlers
If a critical rendering script throws an uncaught error (like a ReferenceError from a missing global), the entire render can halt, leaving a search engine's rendering crawler with a blank or partial page. Wrapping risky rendering logic in try/catch with a sensible fallback keeps at least some content visible and indexable.
Best Practices
Never Leave a catch Block Empty
An empty catch block silently discards the error, hiding real bugs from both developers and monitoring tools. At minimum, log the error (console.error or a reporting service) even if you don't have specific recovery logic for it.
Only Catch Errors You Can Actually Handle
Wrapping an entire function body in a single broad try/catch can mask unrelated bugs alongside the one error you actually expected. Keep try blocks scoped tightly around the specific operation that might fail, so unexpected errors from unrelated code aren't silently swallowed too.
Frequent Bugs
A try/catch wrapped around a setTimeout callback doesn't catch errors thrown inside the callback.
The synchronous try/catch finishes running (and its call stack is gone) long before the asynchronous setTimeout callback ever executes, so an error thrown inside that callback has no enclosing try/catch to be caught by. Put the try/catch inside the callback function itself, not around the setTimeout() call.
Real-World Examples
Validating and Catching a Custom Error in a Form Handler
A signup form needed to reject an invalid age value with a clear, specific error message instead of silently accepting bad data or crashing the page.
function setAge(age) {
if (age < 0 || age > 130) {
throw new Error('Please enter a realistic age.');
}
return age;
}
try {
setAge(-5);
} catch (error) {
showFormError(error.message);
}