Lesson 4.1Lesson 16 of 24
Handling errors
Given a scenario, handle errors properly.
Key points
- 1finally always runs, after try or catch, even when they return. A return inside finally replaces whatever try or catch returned or threw.
- 2Throw Error objects, not strings: only an Error carries name, message and stack. Extend Error for custom types and set name.
- 3Catch only what you can handle. Check the type with instanceof and rethrow everything else, so real bugs are not hidden.
- 4try/catch sees an async failure only through await. A promise returned or started without await rejects later, outside the try block.
- 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