try...catch...finally
try...catch...finally — the core idea
try/catch handles thrown exceptions and rejected awaited Promises in async functions. finally executes when control leaves the try/catch path, whether successful or failed. It is useful for releasing resources or resetting UI loading state.
What you’ll learn
- Explain try...catch...finally with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The Error is thrown, then the catch block narrows unknown to Error and prints unavailable. finally runs after the catch and prints cleanup.
Keep the boundary clear: finally does not magically undo side effects. A return inside finally can override an earlier return or thrown error, so avoid that pattern.
See the idea as a flow
Run the complete TypeScript example
Save the code as try-catch-finally.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
async function main(): Promise<void> {
try {
throw new Error("unavailable");
} catch (error: unknown) {
if (error instanceof Error) console.log(error.message);
} finally {
console.log("cleanup");
}
}
main().catch(console.error);Verified output
unavailable
cleanupBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable try-catch-finally.ts; run: node try-catch-finally.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The Error is thrown, then the catch block narrows unknown to Error and prints unavailable. finally runs after the catch and prints cleanup.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
finally does not magically undo side effects. A return inside finally can override an earlier return or thrown error, so avoid that pattern.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Replace throw with await Promise.reject(new Error("failed")) and predict the same cleanup order.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
try/catch handles thrown exceptions and rejected awaited Promises in async functions.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.