Search⌘ K

Error Handling

Explore how to manage errors in JavaScript by using try-catch blocks and throw statements for synchronous code, and apply error handling techniques with callbacks, promises, and async-await in asynchronous programming. Understand the control flow for errors and how to prevent program interruptions, improving your ability to write robust JavaScript code.

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.

Node.js
try{
console.log('entered try block');
undefinedFunc(); // invoke undefined func
console.log('invoked func in try block'); // will not be executed
} catch (err){
console.log('entered catch block');
console.log("Err:", err);
console.log('Printed error');
}

In the code above, we invoke an undefined function undefinedFunc, causing an error (line 3). Using the try and catch statements, we prevent the program from interrupting which would happen with this error. Moreover, we ...