What is Error Handling?
Error handling is the process of anticipating, detecting, and responding to errors in your code. Proper error handling prevents your application from crashing and provides useful feedback.
💡 Key insight
Good error handling makes your code more robust and user-friendly. Plan for errors just like you plan for success cases.
try...catch
The try...catch statement allows you to handle errors gracefully.
try {
// Code that might throw an error
let result = riskyOperation();
console.log(result);
} catch (error) {
// Code to handle the error
console.error("Something went wrong:", error.message);
}
The throw Statement
Use throw to create custom errors.
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
divide(10, 0);
} catch (error) {
console.error(error.message);
}
The finally Block
Code in finally always runs, regardless of whether an error occurred.
try {
// Risky code
} catch (error) {
// Handle error
} finally {
// Always runs (cleanup, close connections, etc.)
}
Custom Error Types
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateUser(user) {
if (!user.name) {
throw new ValidationError("Name is required");
}
}
Common Mistakes
- Using
try...catcheverywhere (only use where errors are expected) - Swallowing errors without logging or handling them
- Using
catchwithout checking the error type - Throwing non-Error objects (always use
new Error())
Quick Quiz
1. What does try...catch do?
2. What keyword is used to create a custom error?
3. When does the finally block run?
Summary
try...catchhandles errors gracefullythrowcreates custom errorsfinallyruns regardless of errors- Create custom error types by extending
Error - Don't swallow errors — log them
- Check error types before handling
