Background

Due to the environment and nature of working with asynchronous tasks, we can get many potential errors. Therefore, we should expect such cases and know how to fix them.

Introduction to try and catch statements

try and catch statements work side by side to try and execute a set of instructions to catch errors. You can specify a certain response for any possible error.

Syntax

The syntax of the try and catch blocks is like this.

try {
  // execute statements
} catch (err){
  // handle error err received from try block
}

The above syntax adds any number of instructions in the try block. For any error within the try block, the instruction execution stops within the block. The control then jumps to the catch block. The catch block will handle the error, accessible by the variable err. Learn from the example below.

Get hands-on with 1200+ tech skills courses.