Learn Basic Error Handling on Javascrpt : Try-Catch and Async/Await

koshirok096

koshirok096

Posted on June 11, 2023

Learn Basic Error Handling on Javascrpt : Try-Catch and Async/Await

Introduction

Hello guys! In this article, I'd try to briefly summarize Try-Catch. I have often used Try-Catch vaguely, so I decided to write this article to organize the things in my mind. Sorry for my sentences are not well-sophisticated because I'm also still JS learner, but I hope it can be of some help.

Try-Catch

  • Try-Catch statement is the syntax which mainly used for error handling in JavaScript.
  • The code in the try block is executed and if an exception (error) is thrown / caught.
  • catch blocks are executed when an exception is thrown and code is written to handle it appropriately.
  • The parameters in the catch block (usually called error) contain information about the exception that occurred.
  • finally block is option that can be added to Try-Catch statements. It is used to specify code that must be executed whether or not an exception is raised.
  • catch blocks are optional. In other words, the Try-Catch statement can be used with 3 patterns (try.... .catch, try.... .finally, try.... .catch.... .finally).
  • Try-Catch statements allow you to deal with exceptions without crashing your program when they occur.
async function tryCatchFunc() {
  try {
    // Code that may raise an exception
    const result = await someFunction(); 
    console.log(result); // This line is not executed if an exception occurs
  } catch (error) {
    console.error('You got an error:', error); 
  } finally {
    console.log('All processes are done'); // must be executed whether or not an exception is raised
  }
}
Enter fullscreen mode Exit fullscreen mode

Async/await

async is a function that performs asynchronous operations, and await is used to wait until an asynchronous operation completes and receive its results.

Since await cannot work in top-level code, it must be wrapped in an async function like above code.

Within the async function, asynchronous processing portions can be written serially - You can use Try-Catch blocks to provide error handling, for asynchronous processing.

The async/await syntax is a more intuitive way to work with Promise. I will not go into this at this time, but some other time.

Outro

Since there are so MANY opportunities to use Try-Catch statements in a web development, learning the basic error handling will be a great help for beginners. Thank you for read, happy coding!

💖 💪 🙅 🚩
koshirok096
koshirok096

Posted on June 11, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related