Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Keywords and Declarations

TypeScript try, catch and finally

Reference for try, catch and finally in TypeScript: the unknown type of caught values, useUnknownInCatchVariables, narrowing errors, optional catch binding and finally semantics.

try runs code that might throw. If it does, control jumps to catch, which receives the thrown value. finally runs afterwards whether or not anything was thrown, which makes it the place for cleanup.

The key TypeScript fact: anything can be thrown in JavaScript (strings, numbers, plain objects), so a caught value cannot be assumed to be an Error. With strict (via useUnknownInCatchVariables, on since TypeScript 4.4) the catch variable has type unknown and must be narrowed before use.

TypeScript
try {
  riskyThing();
} catch (err) {         // err: unknown
  if (err instanceof Error) console.log(err.message);
} finally {
  cleanup();
}

Try it

TypeScript Narrowing an unknown error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Using the error without narrowing fails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Optional catch binding, finally and returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
try {
  // code that may throw
} catch (error) {
  // error: unknown (or any without useUnknownInCatchVariables)
} finally {
  // always runs
}

try { ... } catch { ... }          // optional catch binding
try { ... } finally { ... }        // no catch: errors propagate
Part Description
try block Code watched for thrown values.
catch (e) Receives the thrown value. You may annotate it only as unknown or any.
finally Runs after try/catch, even after return, break or an uncaught throw.

Errors and edge cases:

  • Annotating the catch variable with another type is error TS1196 ("Catch clause variable type annotation must be 'any' or 'unknown' if specified").
  • Reading .message on the unknown value is error TS18046 ("'err' is of type 'unknown'.").
  • A try needs a catch, a finally, or both; otherwise it is a syntax error (TS1472).
  • A return or throw inside finally overrides whatever the try or catch block produced.

Usage notes

  • Narrow before use. Use instanceof Error, a custom type guard, or a schema check. Never cast with as Error without a check: a library may throw a string.
  • useUnknownInCatchVariables is part of strict. Turning it off makes the variable any, which hides mistakes.
  • Custom errors. Extend Error and set name; with ES2015+ targets instanceof works for subclasses. The cause option (new Error("x", { cause })) is available in ES2022 libs.
  • Async code. try/catch catches rejections only when you await the promise inside the block. See async and await.
  • Result types. For expected failures, returning a result type is often clearer than throwing; see error handling and Result and Either types.
  • No typed exceptions. TypeScript has no throws clauses; document thrown errors in comments or return types.
  • Scoping. Variables declared in try are not visible in catch or finally.
  • Performance. Entering a try is cheap in modern engines; throwing is the expensive part.