Handling Errors in TypeScript


Functional programming languages such as TypeScript and JavaScript provide a way to handle errors using the try-catch blocks. The try block catches the errors, and the catch block handles the errors.  In this tutorial, we will learn to handle errors in TypeScript.

There are mainly 7 types of errors in TypeScript. Here, we will learn all types of errors one by one.

  • Range error − If we try to access anything out of range, TypeScript will throw a range error. For example, accessing the array index for a large number value such as 10^100.

  • Reference error − If we try to access the variable without declaring it, TypeScript throws a reference error. For example, without declaring the string variable, apply the toLowerCase() method on that variable.

  • Syntax error − If we write the code with the wrong syntax, TypeScript throws a syntax error. For example, 10***10 is a syntax error as *** is not representing any operator in TypeScript.

  • Type error − It occurs due to variable type mismatch. For example, removing the decimal part of the string variable using the Math.ceil() method in TypeScript.

  • URI error − It can occur while encoding or decoding the URI in TypeScript. For example, passing an invalid parameter to the decodeURI() function returns the URI error.

  • Eval error − These errors occur while using the eval() function in TypeScript. We can use the eval() function to evaluate the expressions.

  • Internal error − This kind of error occurs internally. For example, It can occur if stack size increases out of the limit.

We have looked at the different types of errors. Now, we will learn to handle the errors using the try, catch and finally block.

Use the try, catch, and finally block

The first question arises − what is the try, catch, and finally block? The try block can contain the code with errors. If any error occurs, it throws the error and stops executing the code from the line where it occurred.

As the name suggests, the catch block is used to catch and handle errors. We can write the code to handle the errors in the catch block according to the different eros. There can be multiple catch blocks for a single try block. We can create a different catch block to handle different kinds of errors, such as syntax and reference errors.

The finally block contains the code that is always necessary to execute before program termination. For example, database connection closing or file closing, which we had opened in the try block before the error occurred.

Syntax

Users can follow the syntax below to use the try, catch, and finally block.

try {
   //  Code with error
} catch {
   // handle the error
} finally {
   // execute the code before the program termination
}

Example 1

In the example below, we have demonstrated the use of the try-catch block to handle the errors in TypeScript. In the try block, we have thrown the error by creating a new instance of the error. The catch block catches and handles that error by printing some messages and errors on the screen. Also, users can see in the output that the “End of the try block” message is not printed as it is written in the line after the error occurred in the line.

try {
   // This should generate syntax error.
   throw new SyntaxError("Error occured inside the syntax.");
   //   this code will not execute.
   console.log("End of the try block");
} catch (error) {
   // control will be at here, after throwing the error from try block.
   console.log("Inside the catch block.");
   console.log("The error is " + error);
}

On compiling, it will generate the following JavaScript code −

try {
   // This should generate syntax error.
   throw new SyntaxError("Error occured inside the syntax.");
   //   this code will not execute.
   console.log("End of the try block");
}
catch (error) {
   // control will be at here, after throwing the error from try block.
   console.log("Inside the catch block.");
   console.log("The error is " + error);
}

Output

The above code will produce the following output −

Inside the catch block.
The error is SyntaxError: Error occured inside the syntax.

Example 2

In the example below, we have created the function inside the try block. It takes two parameters. The first parameter can be any value; another should be a number. Also, it always returns either number or object of the ReferenceError.

Inside the errofunc() function, we check that if both parameters are numbers, return the sum of the number; Otherwise, return the error. In the output, we can see that the first function call will execute properly, and the second function call will create an error.

try {
   // Creating the function which returns an number or error
   function errorfunc(num1, num2: number): number | ReferenceError {
      // If both parameters of type number, then return addition. 
      // Otherwise throw reference error.
      if (typeof num1 == "number" && typeof num2 == "number") {
         console.log(num1 + num2);
      }
      //  Throwing the new instance of the reference error.
      throw new ReferenceError("Parameter/s are not type of numbers.");
   }
   //   This will throw an error.
   errorfunc("11", 12);
} catch (error) {
   console.log("Inside the catch block.");
   console.log("The error is " + error);
} finally {
   // This will execute always
   console.log(
      "Inside the finally block to execute the code before program termination."
   );
}

On compiling, it will generate the following JavaScript code −

try {
   // Creating the function which returns an number or error
   function errorfunc(num1, num2) {
      // If both parameters of type number, then return addition. 
      // Otherwise throw reference error.
      if (typeof num1 == "number" && typeof num2 == "number") {
         console.log(num1 + num2);
      }
      //  Throwing the new instance of the reference error.
      throw new ReferenceError("Parameter/s are not type of number.");
   }
   //   This will throw an error.
   errorfunc("11", 12);
}
catch (error) {
   console.log("Inside the catch block.");
   console.log("The error is " + error);
}
finally {
   // This will execute always
   console.log("Inside the finally block to execute the code before program termination.");
}

Output

The above code will produce the following output −

Inside the catch block.
The error is ReferenceError: Parameter/s are not type of number.
Inside the finally block to execute the code before program termination.

We learned to handle errors in this tutorial. We used the try, catch, and finally block to handle the errors. However, handling errors in TypeScript is similar to handling errors in JavaScript but we have to focus on the error types also in TypeScript.

Updated on: 19-Dec-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements