VOOZH about

URL: https://www.geeksforgeeks.org/typescript/how-to-use-try-catch-and-finally-in-typescript/

⇱ How to use Try Catch and Finally in TypeScript ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to use Try Catch and Finally in TypeScript ?

Last Updated : 29 Jul, 2024

The try, catch and finally blocks are used for error handling and state management while performing asynchronous tasks. It is an effective way to handle errors and state on the web page. This tutorial will explain to you the use of the try, catch, and finally statements practically.

Explanation:

  • try: The try block will run a block of code and check for its correctness and errors.
  • catch: The catch block will catch the error thrown by the try block and print it to your desired location.
  • finally: The final statement runs always irrespective of try and catch, it is independent of them.

Syntax:

try{
// A block of code to check for errors
}
catch(error){
// Displays error thrown by the try block
}
finally{
// Runs irrespective of try and catch blocks
}

Example: The below code example implements the try-and-catch blocks in TypeScript.

Output:

Example: The below code example implements the try, catch and finally to fetch data from an API.

Output:

Comment
Article Tags:
Article Tags:

Explore