codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

TypeScript

43 / 60 topics
42Error Handling in TypeScript43Try/Catch44Custom Errors
Tutorials/TypeScript/Try/Catch
🔷TypeScript

Try/Catch

Updated 2026-05-15
10 min read

Try/Catch

Introduction

In TypeScript, as in many programming languages, error handling is a crucial aspect of writing robust and reliable code. Errors can occur due to various reasons such as invalid user input, unexpected data formats, or issues with external systems. Proper error handling ensures that your application can gracefully handle these situations without crashing.

One of the primary mechanisms for error handling in TypeScript (and JavaScript) is the try/catch block. This structure allows you to attempt a piece of code and catch any errors that might occur during its execution, enabling you to handle them appropriately.

Concept

The try/catch block consists of two main parts:

  1. Try Block: This is where you place the code that might throw an error.
  2. Catch Block: If an error occurs in the try block, control is transferred to the catch block, where you can handle the error.

Optionally, you can also include a finally block, which will execute regardless of whether an error was thrown or not. This is useful for cleanup activities like closing files or releasing resources.

Here's the basic syntax:

try {
  // Code that might throw an error
} catch (error) {
  // Handle the error
} finally {
  // Optional: Code to execute after try/catch, regardless of outcome
}

## Examples

### Basic Try/Catch Example

Let's start with a simple example where we attempt to divide two numbers and handle any potential division by zero errors.

```typescript
<CodeBlock language="typescript">
{`function divide(a: number, b: number): number {
  try {
    if (b === 0) {
      throw new Error("Cannot divide by zero");
    }
    return a / b;
  } catch (error) {
    console.error(error.message);
    return NaN; // Return Not-a-Number to indicate an error
  }
}

console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: Cannot divide by zero`}
</CodeBlock>

In this example:
- The `divide` function attempts to perform a division.
- If the divisor (`b`) is zero, an error is thrown with a descriptive message.
- The catch block catches this error and logs the message to the console.
- It then returns `NaN` to indicate that the operation failed.

### Catching Specific Errors

You can also catch specific types of errors by checking the type of the caught error. This is useful when you want to handle different kinds of errors differently.

```typescript
<CodeBlock language="typescript">
{`class CustomError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "CustomError";
  }
}

function riskyOperation() {
  try {
    throw new CustomError("Something went wrong!");
  } catch (error) {
    if (error instanceof CustomError) {
      console.error(\`Caught a custom error: \${error.message}\`);
    } else {
      console.error("An unexpected error occurred");
    }
  }
}

riskyOperation();`}
</CodeBlock>

In this example:
- A custom error class `CustomError` is defined.
- The `riskyOperation` function throws an instance of `CustomError`.
- The catch block checks if the caught error is an instance of `CustomError` and handles it accordingly.

### Using Finally

The `finally` block is useful for executing code that should run regardless of whether an error was thrown or not. This can be used for cleanup tasks.

```typescript
<CodeBlock language="typescript">
{`function openFile(filePath: string): void {
  let file = null;
  try {
    file = open(filePath, 'r');
    // Read from the file
  } catch (error) {
    console.error(\`Failed to open file: \${error.message}\`);
  } finally {
    if (file !== null) {
      close(file);
    }
  }
}

openFile("example.txt");`}
</CodeBlock>

In this example:
- The `openFile` function attempts to open a file.
- If an error occurs, it is caught and logged.
- Regardless of whether an error occurred or not, the file is closed in the finally block.

## What's Next?

Now that you understand how to use try/catch blocks for basic error handling, you might want to explore more advanced topics such as:

- **Custom Errors**: Creating custom error classes to handle specific scenarios.
- **Error Propagation**: Understanding how errors propagate through function calls and how to handle them at different levels of your application.

By mastering these concepts, you'll be well-equipped to write robust TypeScript applications that can handle unexpected situations gracefully.

PreviousError Handling in TypeScriptNext Custom Errors

Recommended Gear

Error Handling in TypeScriptCustom Errors