Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The try...catch statement is a control flow construct used to handle runtime exceptions. It consists of a try block containing code that may throw an exception, a catch block that executes if an exception is thrown, and an optional finally block that executes unconditionally after the try and catch blocks have resolved.
try {
  // Code that may throw an exception
} catch (error) {
  // Exception handling logic
} finally {
  // Unconditional execution logic (optional)
}

TypeScript Catch Variable Typing

In TypeScript, the most critical distinction regarding try...catch is the typing of the catch clause variable. Because JavaScript permits throwing any value (including strings, numbers, objects, or null), TypeScript enforces strict rules on how the caught exception is typed. 1. Explicit Type Annotations are Invalid TypeScript does not allow explicit type annotations on the catch variable. Attempting to define the error type directly results in a compiler error.
// ❌ Syntax Error: Catch clause variable type annotation must be 'any' or 'unknown' if specified.
try {
  // ...
} catch (error: Error) { 
  // ...
}
2. The unknown Type Default As of TypeScript 4.4, if the useUnknownInCatchVariables compiler option is enabled (which is the default under strict mode), the catch variable is implicitly typed as unknown. Prior to 4.4, or if the flag is disabled, it defaults to any. You can explicitly annotate the variable as any or unknown, but unknown is the recommended and safest approach.
try {
  // ...
} catch (error: unknown) { // Valid explicit annotation
  // ...
}

Type Narrowing in Catch Blocks

Because the caught error is typed as unknown, you cannot directly access properties like error.message or error.code. You must perform type narrowing using type guards (instanceof, typeof, or custom type predicate functions) to safely interact with the exception payload.
try {
  throw new Error("Execution failed");
} catch (error) {
  // 'error' is typed as 'unknown'

  if (error instanceof Error) {
    // Narrowed to 'Error'. Safe to access .message
    console.error(error.message); 
  } else if (typeof error === "string") {
    // Narrowed to 'string'.
    console.error(error.toUpperCase());
  } else {
    // Remains 'unknown'. Fallback handling.
    console.error("An unexpected error payload was thrown:", error);
  }
}

Asserting Custom Error Types

If you are working with custom error classes and are certain of the exception type being thrown, you can use type assertions (as) after catching the error. However, this bypasses TypeScript’s safety checks and should be used cautiously.
class DatabaseError extends Error {
  code: number;
  constructor(message: string, code: number) {
    super(message);
    this.code = code;
  }
}

try {
  // ...
} catch (error) {
  // Type assertion forces the compiler to treat 'error' as 'DatabaseError'
  const dbError = error as DatabaseError;
  console.log(dbError.code);
}
Master TypeScript with Deep Grasping Methodology!Learn More