> ## 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.

# TypeScript Try-Catch

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.

```typescript theme={"dark"}
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.

```typescript theme={"dark"}
// ❌ 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.

```typescript theme={"dark"}
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.

```typescript theme={"dark"}
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.

```typescript theme={"dark"}
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);
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
