Course contentsShow
← JavaScript
Lesson 1131 of 2,72326. Error HandlingFree lesson

Catching Different Error Types

Using instanceof checks to handle specific error types like TypeError or ReferenceError differently.

Catching Different Error Types

You'll learn how to identify and handle specific kinds of errors differently using instanceof checks inside your catch block.

Why Different Error Types Matter

Not all errors are created equal. JavaScript has built-in error types like TypeError (wrong data type), ReferenceError (undefined variable), SyntaxError (code structure problems), and more. When an error occurs, you might want to respond differently depending on what kind of error it is.

Using instanceof to Check Error Types

Inside your catch block, you can use the instanceof operator to test what type of error was caught. This lets you provide specific handling for different scenarios:

try {
  let result = unknownVariable.toUpperCase();
} catch (error) {
  if (error instanceof ReferenceError) {
    console.log("Variable doesn't exist!");
  } else if (error instanceof TypeError) {
    console.log("Wrong type of value used!");
  } else {
    console.log("Something else went wrong:", error.message);
  }
}

Real-World Example

function processData(data) {
  try {
    return data.trim().toUpperCase();
  } catch (error) {
    if (error instanceof TypeError) {
      console.log("Expected a string, got something else");
      return "";
    } else if (error instanceof ReferenceError) {
      console.log("Data variable is missing");
      return "";
    } else {
      throw error; // Re-throw unexpected errors
    }
  }
}

Think of this like a mail sorting facility: instead of dumping all "problem mail" into one bin, you sort it by type of problem—wrong address, missing stamp, damaged package—so each can be handled appropriately.

Key Takeaway: Use instanceof inside catch blocks to identify specific error types and provide targeted responses for TypeError, ReferenceError, and other built-in error classes.