Error Handling in JavaScript: Try, Catch, Finally

β οΈ What Are Errors in JavaScript?
Errors are problems that occur during code execution and stop your program from running correctly.
πΉ Common Types of Errors
Syntax Error
Mistake in code structureconsole.log("Hello" // missing )Reference Error
Using a variable that is not defined
console.log(name); // name is not definedType Error
Wrong operation on a data type
let num = 10; num.toUpperCase(); // number has no toUpperCase()Range Error
Value out of allowed range
let arr = new Array(-1);
π¨ Real Runtime Error Example
let user = null;
console.log(user.name); // β TypeError
π This crashes your app if not handled.
π οΈ Using try...catch
try...catch helps handle errors gracefully instead of crashing.
try {
let user = null;
console.log(user.name);
} catch (error) {
console.log("Something went wrong:", error.message);
}
β Output:
Something went wrong: Cannot read properties of null
π Execution Flow (Try β Catch β Finally)
Start
β
Try Block
β
Error?
/ \
Yes No
β β
Catch Skip Catch
β
Finally (always runs)
β
End
π§© The finally Block
finally always runs β whether an error occurs or not.
try {
console.log("Try block running");
} catch (err) {
console.log("Error caught");
} finally {
console.log("Always runs");
}
π― Throwing Custom Errors
You can create your own errors using throw.
function withdraw(amount) {
if (amount > 1000) {
throw new Error("Limit exceeded");
}
return "Withdrawal successful";
}
try {
withdraw(2000);
} catch (err) {
console.log(err.message);
}
π Real-World Example (Bank System)
function transfer(balance, amount) {
try {
if (amount > balance) {
throw new Error("Insufficient balance");
}
console.log("Transfer successful");
} catch (err) {
console.log("Transaction failed:", err.message);
} finally {
console.log("Transaction attempt completed");
}
}
transfer(500, 700);
π‘ Why Error Handling Matters
β Prevents App Crash
Without handling β app stops β
With handling β app continues β
β Graceful Failure
Instead of breaking:
"Error occurred"
You show:
"Something went wrong, please try again"
β Better Debugging
Error messages help identify bugs faster
Stack traces show where the issue occurred
β Improves User Experience
Users donβt see broken screens π
π§ Graceful Failure Example
β Bad:
console.log(user.name);
β Good:
if (user) {
console.log(user.name);
} else {
console.log("User not available");
}
π Debugging Benefits
Helps locate exact issue
Saves development time
Makes code maintainable
Easier testing & logging
π― Quick Summary
Errors are unavoidable β handling them is essential
Use
try...catchto prevent crashesUse
finallyfor cleanup tasksUse
throwto create custom errorsAlways aim for graceful failure



