Book Your Free Call

How does try catch work in TypeScript?

Tim Mouskhelichvili
Tim Mouskhelichvili
3 minutes to read

In TypeScript, just like in JavaScript, the try catch statement is used to handle errors in your code. It consists of three statements:

  1. The try statement that defines the code to try (or run).
  2. The catch statement that defines the code that handles the errors.
  3. The optional finally statement that defines the code that runs at the end either way.

Here is an example of the try catch finally statements in action.

typescripttry {
    functionThatThrowsError();
} catch (e: any){
    console.log(e);
} finally {
    console.log('finally');
}

In this article, I will go over, in detail, about how does the try catch statement work, answer common questions, as well provide TypeScript specific examples.

Let's get to it 😎.

The definition

A try catch statement handles errors in a specific code block.

It consists of two mandatory statements, try and catch, and it follows this flow.

  1. The code inside the try statement runs.
  2. If the try statement throws a runtime error, the code block inside the catch statement executes.

Here is the basic syntax for a try catch statement.

typescripttry {
    // code to try
} catch {
    // code that handles the error
}

As you can see, the catch parameter is optional.

This syntax, called optional catch binding, may require a polyfill for older browsers.

Alternatively, you can set up a catch parameter, if you need one.

typescripttry {
    // code to try
} catch (e: any) {
    // code that handles the error
    console.log(e.name);
    console.log(e.message);
}

In TypeScript, a catch parameter can only be of type any or unknown.

An Error object has two properties that you can use (message and name).

There are two important things to know about the try catch statement:

  1. It only works for runtime errors, this means that it will not work for syntax errors.
  2. It only works for synchronous code.

You can put almost any code statements that you want inside the try block... For loop, switch statement, while, etc...

The finally statement

The finally statement ALWAYS runs regardless after a try catch statement.

The code inside the finally statement will even run if the catch statement throws an error or returns.

typescripttry {
    // code to try
} catch (e: any) {
    // code that handles the error
} finally {
    // code that will run regardless
}

The throw statement

The throw statement allows the developer to create custom errors that you can throw in your code.

Here is an example of this.

typescripttry {
    throw Error('This is an error');
} catch (e: any) {
    console.log('error');
    console.log(e.message);
} finally {
    console.log('finally');
}

// outputs: 'error'
// outputs: 'This is an error'
// outputs: 'finally'
typescript try catch

How to catch a specific error?

You can catch a specific error inside a catch statement by using the instanceof operator.

typescripttry {
    // Code
} catch (e: any) {
    if (e instanceof YourException){
        // code that runs for this exception.
    } else if (e instanceof YourException2){
        // code that runs for this exception.
    }
}

As you can see, we are executing different parts of the code based on the error that we get.

How to use try catch with async/await?

The try catch will catch all errors inside an async function. We just need to be sure to await the function.

Here is an example of an async function inside a try catch statement.

typescripttry {
    await createUser({
        name: 'Tim Mousk'
    });
} catch (e: any) {
    // handles the error
    console.log(e);
}

Alternatively, you can use the promise catch built-in method.

typescriptawait createUser({
    name: 'Tim Mousk'
}).catch((e: any) => {
    // handles the error
    console.log(e);
});

What are some best practices?

  1. Throw your own custom errors, this will help you with development and debugging.
  2. For large applications, you need to implement remote exception logging with window.onerror. This will help you debug your application.
  3. Don't use browser non-standard methods.

Final thoughts

As you can see, understanding the try catch statement is no rocket science.

It is actually quite easy to master.

You have three statements, try, catch, and finally, that do exactly the action in their name. The finally statement is optional. Also, you can throw an Error, with the throw statement.

That's it... That's the big picture.

typescript try catch

When it comes to, the try catch statement, the only difference between JavaScript and TypeScript is that with TypeScript you can specify the type of the catch clause parameter.

I hope you enjoyed reading through this article, please share it with your fellow developers.

Don't hesitate to ask questions, I always respond.

Comments (0)