Error Handling in JavaScript: Try, Catch, Finally
Source: Dev.to
🚨 What Are Errors in JavaScript?
Errors are problems that occur during code execution (runtime).
Example
console.log(x); // ❌ ReferenceError: x is not definedCommon Types of Errors
- ReferenceError – variable not defined
- TypeError – wrong type usage
- SyntaxError – invalid code
😵 The Problem Without Error Handling
function divide(a, b) {
return a / b;
}
console.log(divide(10, 0));
console.log("This may still run...");Some errors can break your app or cause unexpected behavior.
💡 Using try and catch
The try...catch block lets you handle errors safely.
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.log("Something went wrong:", error.message);
}📊 Flow
try block runs
↓
error occurs?
↓ yes
catch block runs
↓
program continues safely📥 Understanding the catch Block
try {
console.log(x);
} catch (error) {
console.log(error.name); // ReferenceError
console.log(error.message); // x is not defined
}The error object provides useful debugging information.
🧹 The finally Block
The finally block always runs—whether an error occurs or not.
try {
console.log("Trying...");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("This always runs");
}📊 Execution Order
try → catch (if error) → finally🔥 Throwing Custom Errors
You can create your own errors using throw.
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Insufficient balance");
}
return balance - amount;
}
try {
withdraw(1000, 1500);
} catch (err) {
console.log(err.message);
}🧠 Why Use Custom Errors?
- Better debugging
- Clear error messages
- Control program flow
🛠️ Real-World Example
function parseJSON(data) {
try {
return JSON.parse(data);
} catch (err) {
console.log("Invalid JSON");
return null;
}
}❓ Why Error Handling Matters
- ✅ 1. Prevents Crashes – Your app keeps running even when something fails.
- ✅ 2. Better User Experience – Users see meaningful messages instead of broken screens.
- ✅ 3. Easier Debugging – You get clear insights into what went wrong.
- ✅ 4. Graceful Failure
Bad:
// app crashes ❌Good:
// show error message ✅
// continue execution ✅⚠️ Important Notes
try...catchonly works for runtime errors.- It does not catch syntax errors.
- Works synchronously (async needs special handling like
async/await).
🧠 Best Practices
- Keep
tryblocks small. - Use meaningful error messages.
- Don’t ignore errors silently.
- Use
finallyfor cleanup (closing resources, etc.).
🚀 Final Thoughts
Error handling is not optional—it’s essential. Using try, catch, and finally, you can:
- Build robust applications.
- Handle failures gracefully.
- Improve debugging and maintenance.
🧠 Quick Summary
- Errors happen at runtime.
try→ test code.catch→ handle errors.finally→ always runs.throw→ create custom errors.