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.
try { riskyThing(); } catch (err) { // err: unknown if (err instanceof Error) console.log(err.message); } finally { cleanup(); }
Try it
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.
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.
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
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
.messageon theunknownvalue is error TS18046 ("'err' is of type 'unknown'."). - A
tryneeds acatch, afinally, or both; otherwise it is a syntax error (TS1472). - A
returnorthrowinsidefinallyoverrides 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 withas Errorwithout a check: a library may throw a string. useUnknownInCatchVariablesis part ofstrict. Turning it off makes the variableany, which hides mistakes.- Custom errors. Extend
Errorand setname; with ES2015+ targetsinstanceofworks for subclasses. Thecauseoption (new Error("x", { cause })) is available in ES2022 libs. - Async code.
try/catchcatches rejections only when youawaitthe 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
throwsclauses; document thrown errors in comments or return types. - Scoping. Variables declared in
tryare not visible incatchorfinally. - Performance. Entering a
tryis cheap in modern engines; throwing is the expensive part.