Curriculum / Advanced / Lesson 24

Error Handling

try/catch, throw, and creating custom errors.

24 of 30
advanced 📖 6 min read 🎯 3 questions

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

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

Back to curriculum