TypeScript Try Catch Statement

Learn via video courses
Topics Covered

Overview

TypeScript is described by Microsoft as a superset of JavaScript. What do I mean when I say this?

Every valid JavaScript code is likewise a valid TypeScript code. TypeScript can accomplish more than its predecessor, but it cannot do less. Otherwise, project migration would be far more complex, and developer acceptance would be significantly lower.

Introduction

Many JavaScript topics are covered by TypeScript. Also, the dubious ones. Some error-handling scenarios are rather intriguing, but this article will help you navigate through the jungle of typescript to try to catch!

As a result, they also took the terrible ones. Such as exception handling. When broken down, the error handling is quite similar to that of C#.

The throw keyword is used to raise an exception. And when you correctly guess this one, you will also correctly predict the next : try and catch are used to manage them. As a result, whether the exception is a default or a user-defined one is not important.

There is no need for a catch here because try-finally is sufficient. Finally, it ensures that any unnecessary memory allocations are erased. However, this is not a new phenomenon. It has been in existence for many years.

The Try Catch Blocks in Typescript allows you to manage any or all of the mistakes that may occur in your application. These mistakes are sometimes referred to as exceptions.

A try-catch statement has a try block containing statements that may throw an exception. Then you write a catch block that contains the statements that are executed when any statement in the try block throws an exception.

If an exception is thrown within a try block, the catch block will capture it. Otherwise, the exception is forwarded to the function that is called it. This exception sending continues until the exception is caught or the application terminates with a runtime error.

Syntax

Following is the general syntax for Try Catch Blocks in Typescript :

Let's look at the images below to show how many Try Catch Blocks in Typescript may be made, as well as the better version instead of too many Try Catch Blocks in Typescript.

Example - 1 :

In this example, we will use numerous Try Catch Blocks in Typescript to capture various errors from separate functions that each generate a distinct error, and then we will attempt to print those error messages one after the other.

Output :

In the above example, the insertion of several Try Catch Blocks in Typescript makes the code appear larger and reduces readability to some extent, which no user wants.

In another example, we will try to grasp the alternative approach to capture many functions' thrown errors without using multiple Try Catch Blocks in Typescript, such as examining the alternative way out to decrease the overhead of several Try Catch Blocks in Typescript.

We'll use the callback function notion here (when a function is passed inside of another function as an argument, which is further executed after the completion of the first function is the main function itself). We will use a callback function to capture the errors thrown by each method inside the try block, which will be declared inside a Wrapper Function (also known as a helper function) that will catch all errors thrown by all functions one after the other.

Example - 2 :

In this example, we will utilize the callback function in conjunction with Try Catch Blocks in Typescript to handle the thrown exception.

Output :

The Definition

The keywords 'try' and 'catch' indicate the management of exceptions caused by data or code problems during program execution. A try block is a section of code where exceptions occur. Exceptions from try blocks are caught and handled by a catch block.

Try to describe a set of particular statements that may result in an exception. A catch block captures a certain sort of exception when it will occur. If an exception is not handled by try/catch blocks, it escalates across the call stack until it is caught or the compiler prints an error message.

The try-catch statement combines the try-block with the catch-block or finally-block or both. The try-block will be run first, followed by the catch-block if an exception is thrown. Before ending the control flow of the entire code, the last block is always executed.

Now let's see the need for typescript try catch.

The Need of Try Catch Blocks in Typescript

The following can be some of the reasons behind the existence of Try Catch Blocks in typescript.

  • To put it simply, try/catch blocks are required to catch all failures/ errors returned by various methods.
  • Catching those issues enhances our code's efficiency and, as a result, readability.
  • To capture numerous failures from several functions one after the other, multiple try/catch blocks are necessary.

The Try Catch is the best way to handle errors nowadays because The try...catch statement consists of a try block and either a catch, a finally, or both blocks. The try block code is evaluated first, and if it throws an exception, the catch block code is executed. Before the control flow exits the entire construct, the code in the finally block is always executed. For a better understanding see the following syntax :

Syntax

  • try_Statements :
    The statements that will be carried out.
  • catch_Statements :
    If an exception is thrown in the try-block, this statement gets executed.
  • exception_Variable :
    An optional identification for the captured exception in the catch block. If the catch block does not use the exception's value, omit the exception_Variable and its parentheses, as catch...
  • finally_Statements :
    Statements performed before the control flow leaves the try...catch...finally construct. These statements are executed whether an exception was thrown or caught.

The try phrase is always preceded by a try block. Then there must be a catch block or a finally block. It is also possible to have both a catch and then a block. This provides us with three different ways to express the try statement :

  • try...catch
  • try...finally
  • try...catch...finally

In contrast to other constructions like if and for, the try, catch, and finally blocks must be blocks rather than single words.

Now let's see Finally statement in typescript and try to catch it.

The Finally Statement

The finally block contains statements that will be executed after the try and catch blocks, but before the statements that follow the try...catch...finally block. Control flow will always enter the finally block, where it can go one of two ways :

  • Immediately before the try block, regular execution is completed (no exceptions are thrown).
  • Immediately before the catch block completes regular execution.
  • The try or catch block is run immediately before a control-flow statement (return, throw, break, or continue).

Though an exception is thrown from the try block, even if there is no catch block to handle it, the finally block still executes, and the exception is fired immediately after the finally block completes.

The finally-block is demonstrated in the following example. The code opens a file and then runs statements that use it; the finally-block ensures that the file is always closed after use, even if an exception is thrown.

Control flow statements in the finally block (return, throw, break, continue) will 'mask' any completion value of the try or catch blocks. In this example, the try block attempts to return 1, but before doing so, the control flow is passed to the finally block, which returns the finally block's return value instead.

Output :

Control flow statements in the finally block are generally not a good idea. Use it only for the cleanup code.

We just saw finally statement noe let's see throw the statement in typescript and try catch

The Throw Statement

The typescript type system is useful in most situations, however, it cannot be used when dealing with exceptions.

As an example :

The issue here is twofold (without looking at the code) :

  • There is no way to determine if this function will throw an error when used.
  • It is unclear what type(s) of errors will occur.
  • In many cases, this isn't an issue, but knowing if a function/method may throw an exception can be quite beneficial in a variety of situations, especially when working with multiple libraries.

The type system can be used for exception management by providing (optional) verified exceptions.

I understand that checked exceptions are not universally accepted, but by making it optional (and perhaps inferred? more later), it just offers the ability to add more information about the code that might benefit developers, tools, and documentation.

It will also enable more effective use of meaningful custom mistakes in large, complex applications. Because all javascript runtime faults are of the type Error (or extending types like TypeError), the real type for a function is always type | Error.

The syntax is simple, a function definition can conclude with a throws clause followed by a type :

The syntax for catching exceptions is the same, with the addition of the ability to define the type(s) of error :

Examples :

It's evident here that the function can throw an error and that the error will be a string, so when this method is called, the developer (and the compiler/IDE) is aware of it and can handle it better. So :

It compiles without problems, however

Compilation fails because a number is not a string.

You did great work so far now let's begin with catching errors in typescript try catch

How to Catch a Specific Error ?

No matter how good we are at programming, our scripts may occasionally include mistakes. They can arise as a result of our faults, unanticipated user input, an incorrect server response, or any number of other factors.

In most cases, a script 'dies' (immediately stops) when an error occurs, reporting it to the console.

However, there is a grammar construct try...catch that allows us to 'catch' failures so that the script may do something more logical instead of dying.

Working :

  • The code in try... is the first run.
  • If there were no errors, catch (err) is ignored: the execution proceeds to the conclusion of try and skips catch.
  • If an error occurs, the try execution is terminated, and control is transferred to the beginning of the catch (err). The err variable (we can call it whatever we want) will hold an error object with information about what happened.

how-to-catch-a-specific-error

So, an error inside the try{...} block does not terminate the script; we may address it in the catch.

Some points to keep in mind :

  • try...catch is mainly useful for runtime errors. The code must be runnable for try...catch to work. To put it another way, it should be valid JavaScript.

    It will not operate if the code is syntactically incorrect, such as having mismatched curly braces :

    The JavaScript engine examines the code before running it. Parse-time errors are unrecoverable mistakes that occur during the reading process (from inside that code). This is due to the engine's inability to comprehend the code.

    As a result, try...catch can only handle mistakes in valid code. Such mistakes are sometimes known as 'runtime errors' or 'exceptions'.

  • try...catch works instantaneously. If an exception occurs in 'scheduled' code, such as setTimeout, try...catch will not catch it :

    This is because the function is called after the engine has exited the try...catch construct.

To catch an exception within a scheduled function, try...catch must be present :

How to Use Try Catch with Async/Await ?

Consider the following thought experiment : a method to instruct the JavaScript runtime to halt code execution on the await keyword when used on a promise and continue only once (and if) the promise returned by the function is settled :

When the promise settles, execution proceeds,

  • if the promise was completed, await returns of the value.
  • if the promise was not completed, an error is thrown synchronously that we may catch.

This miraculously (and unexpectedly) makes asynchronous programming as simple as synchronous programming. This thinking experiment requires three items :

  • Function execution can be paused.
  • The ability to insert a value inside the function.
  • The ability to throw an exception within a function.

This is precisely what generators enabled us to achieve! The thought experiment is real, as is the TypeScript / JavaScript async/await implementation.

Generated JavaScript

You don't have to comprehend this, but if you've read up on generators, it's very straightforward. The function foo is easily encapsulated as follows :

where ReturnPromise simply calls the generator function to obtain the generator and then uses the generator. If the value is a promise, next() will then+catch the promise and, depending on the result, will call generator.next(result) or generator.throw(error). That's all!

Async Await Support in typescript

TypeScript has supported Async - Await since version 1.7. Asynchronous functions are prefixed with the async keyword, await suspends execution until an asynchronous function return promise is fulfilled and unwraps the value delivered by the Promise. Only target es6 transpiling directly to ES6 generators was supported.

TypeScript 2.1 introduced the feature to the ES3 and ES5 run-times, so you can use it regardless of the context you're in. It's worth noting that we can utilize async / await with TypeScript 2.1, and that many browsers are supported, having globally introduced a Promise polyfill.

Let's look at this example and this code to see how TypeScript async / await syntax works :

Output :

Conclusion

  • Most of the time, the unexpected can happen, and TypeScript does an excellent job of requiring you to deal with those unusual instances... And you'll probably discover that they aren't as unlikely as you believe.
  • Handling errors in Javascript and Typescript is simple and prevents your application from crashing.
  • When utilizing the finally block, the specific handling of returning results in the try and catch blocks are useful to know, but it should not be misused to avoid writing your code in an anti-pattern approach.
  • If possible, avoid using toss.
  • Your API's users are not required to catch (the compiler does not enforce it). This implies you'll ultimately encounter a runtime error... It's only a matter of time.
  • Throw compels you to keep documents that will soon become stale.
  • The try...catch construct helps handle runtime issues.
  • Because there may be no catch section or finally, simpler structures such as try...catch and try...finally are also acceptable.
  • Even if try...catch is not available, most environments enable us to configure a 'global' error handler to capture failures that 'fall out'. That's a window in-browser. onerror.