CCA Prep

Lesson 4.1Lesson 16 of 24

Handling errors

Given a scenario, handle errors properly.

Handling errorsWhere does the failure happen?Synchronous codetry/catchrethrow what youcannot handleInside an asyncfunctiontry/catch aroundawaitreturn await insidetryA promise chain.catch at theendcovers every stepbefore itA callback run laterHandle insidethe callbackthe outer try hasalready ended

Key points

  1. 1finally always runs, after try or catch, even when they return. A return inside finally replaces whatever try or catch returned or threw.
  2. 2Throw Error objects, not strings: only an Error carries name, message and stack. Extend Error for custom types and set name.
  3. 3Catch only what you can handle. Check the type with instanceof and rethrow everything else, so real bugs are not hidden.
  4. 4try/catch sees an async failure only through await. A promise returned or started without await rejects later, outside the try block.
  5. 5then(onOk, onFail) does not catch errors thrown in onOk. Put catch at the end of the chain instead.
What the exam guide checks here

Objective wording from the exam guide (English).

  • 4.1.K1try/catch/finally, throw, Error types and custom errors
  • 4.1.K2Errors in asynchronous code: rejected promises, catch, try/catch around await
  • 4.1.S1Choose the error handling that catches the failure and keeps the program correct

Lock it in

Answer scenario questions on this topic. Every option comes with an explanation.

Practise 4.1 · 12 questions