Skip to content

Chapter 17 of 33

Error Handling

Throw, catch, translate, preserve, and report synchronous and asynchronous failures.

36 minutes 10 quick checksBy Subha Prasad
Lesson 17 of 33Course navigation

Lesson content

Read, practise, then check your understanding

throw accepts any value, but Error objects provide names, messages, stacks, and causes. Throw specific errors at clear contract boundaries.

Preserve context

function parseConfig(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new SyntaxError("Invalid configuration", { cause: error });
  } finally {
    // unconditional follow-up, not usually return
  }
}

Catch only when you can recover, add context, or report at a boundary. Avoid swallowing errors or returning from finally. Custom Error subclasses can carry stable codes. Promise rejections require awaited try/catch or chain rejection handlers; global unhandled hooks are last-resort reporting, not normal recovery.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes throw?
Which JavaScript term matches this description: A statement causing abrupt completion with any JavaScript value.
Which statement best describes Error?
Which JavaScript term matches this description: The standard base object carrying message and stack information.
Which statement best describes catch?
Which JavaScript term matches this description: A block handling a thrown value from its try region.
Which statement best describes finally?
Which JavaScript term matches this description: A block run after try/catch during normal or abrupt completion.
Which statement best describes cause?
Which JavaScript term matches this description: An Error option preserving the original failure when translating errors.

0 of 10 checks passed

Your progress is saved on this device.

Error Handling | JavaScript Lesson | Subha Prasad