CodeBlanks Logo Icon CodeBlanks

Multiple catch patterns

JavaScript course · Intermediate · Lesson 102/134

Learn to handle different error types inside a single catch block.

Single catch, multiple patterns

JavaScript does not allow multiple catch blocks; instead you branch by error type inside one catch using instanceof. You write a separate handler for each type.

try {
  parseInput(raw);
} catch (err) {
  if (err instanceof SyntaxError) {
    showFormatError(err);
  } else if (err instanceof RangeError) {
    showRangeError(err);
  } else {
    throw err;
  }
}

Leaving unknown errors

Inside a catch block the safest path for unknown error types is to let them bubble. In the else branch rethrow the error or send it to a central handler. Silently swallowing an unknown error makes debugging hard.

Handle the types you know and pass the rest to the caller. This prevents unexpected cases from vanishing.

Exercise Multiple-pattern error handler

Write a function handleError that takes an error parameter. If error instanceof ValidationError call showFormError(error); if error instanceof NetworkError call showRetry(error); otherwise rethrow with throw error.

Show example solution
function handleError(error) {
  if (error instanceof ValidationError) {
    showFormError(error);
  } else if (error instanceof NetworkError) {
    showRetry(error);
  } else {
    throw error;
  }
}

Test yourself

  1. How do you tell a ValidationError apart in a catch block?

    • if (err.name = 'ValidationError')
    • if (err.type === ValidationError)
    • if (err instanceof ValidationError)
    • if (err.is(ValidationError))
    Show answer

    if (err instanceof ValidationError) — Correct! instanceof safely checks the error type.

  2. Type check with instanceof

    if (err ____ ValidationError) {
      showFormError(err);
    }
    Show answer
    if (err instanceof ValidationError) {
      showFormError(err);
    }
  3. Match built-in error types

    SyntaxError
    Syntax error
    RangeError
    Out of range value
    TypeError
    Wrong type
    ReferenceError
    Undefined variable

All lessons in Intermediate