Exceptions and promise basics
An exception interrupts normal control flow. A promise represents the eventual fulfillment or rejection of an operation. In Node.js, try and catch handle synchronous exceptions; when awaiting a promise, a rejection becomes a thrown error at the await expression and can also be caught.
Local practice: The proposed teaching runtime is Node.js 26.13.1 LTS. These original offline examples were executed on Node.js 22.16.0 (Linux x64); execution on the proposed baseline and in ByteMind is not yet verified. No npm dependencies are required. Use a fresh practice directory. Code blocks are static, not a browser-based Node runner.
Catch a synchronous domain error
function checkQuantity(quantity) { if (quantity < 1) throw new Error("Quantity must be positive"); return quantity;}try { console.log(checkQuantity(0));} catch (error) { console.log(error.message);}In the directory containing the files above, run:
node main.mjsExpected standard output:
Quantity must be positiveExpected exit status: 0.
How it works
throw new Error(...) creates an explicit failure. A catch block handles it and can produce a controlled message. An async function returns a promise; a returned value fulfills that promise and an uncaught thrown error rejects it. await inside an async function, or at the top level of an ES module, waits for settlement without blocking the whole Node runtime. It does not turn CPU work into background work. Here each promise is awaited and errors are handled, so there is no unhandled rejection. More scheduling details come later.
Await and handle an async failure
async function findTitle(id) { if (id !== 7) throw new Error("Book not found"); return "River Maps";}console.log(await findTitle(7));try { await findTitle(9);} catch (error) { console.log(error.message);}In the directory containing the files above, run:
node main.mjsExpected standard output:
River MapsBook not foundExpected exit status: 0.
Common mistake
Calling an async function without awaiting or otherwise handling its returned promise does not catch its later rejection with an ordinary surrounding synchronous try/catch. Do not expose arbitrary internal exception messages to real API clients; these examples print deliberately controlled messages.
Try it yourself
Add a second known book ID to findTitle. Test one valid and one missing ID. Explain how the caller receives a fulfilled value or handles a rejection. Keep the .mjs extension for top-level await.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Exceptions and promise basics — knowledge check
Check your understanding of exceptions and promise basics.
What does an async function return to its caller?
What occurs when an awaited promise rejects inside try?
Does await make CPU-heavy JavaScript run on another thread?