JavaScript Error Handling — Write Safer Code

What Are Errors in JavaScript?
👉 Errors are unexpected problems that occur while your code is running.
They stop your program and can break your app if not handled properly.
Example: Runtime Error
console.log(user.name);
👉 If user is not defined → ❌ Error
ReferenceError: user is not defined
Types of Errors (Simple View)
Syntax Error → wrong code format
Runtime Error → happens during execution
Logical Error → code runs but gives wrong result
Why Error Handling Matters
Without error handling:
App crashes 💥
Bad user experience 😞
Hard to debug 🔍
With error handling:
App fails gracefully ✅
You can show friendly messages
Easier debugging
Using try...catch
👉 try...catch lets you handle errors safely
✅ Example
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.log("Something went wrong:", error.message);
}
👉 Code inside try runs
👉 If error occurs → catch handles it
The finally Block
👉 finally always runs (whether error happens or not)
✅ Example
try {
console.log("Trying...");
} catch (err) {
console.log("Error occurred");
} finally {
console.log("This always runs");
}
Throwing Custom Errors
👉 You can create your own errors using throw
✅ Example
function withdraw(amount) {
if (amount > 1000) {
throw new Error("Limit exceeded");
}
return "Transaction successful";
}
try {
withdraw(2000);
} catch (err) {
console.log(err.message);
}
👉 Helps you control error behavior
Graceful Failure (Important Concept)
Instead of crashing:
👉 Show useful messages
try {
let data = JSON.parse("invalid json");
} catch (err) {
console.log("Invalid data format");
}
👉 User doesn’t see scary errors 👌
Real-World Example
async function fetchData() {
try {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
console.log(data);
} catch (error) {
console.log("Failed to fetch data");
} finally {
console.log("Request completed");
}
}
Benefits of Error Handling
Prevent crashes 💥
Improve user experience 😊
Easier debugging 🔍
Better code quality 📈
Final Thoughts
👉 Errors are normal in programming
👉 Handling them properly makes you a professional developer



