JavaScript Try & Catch

JavaScript provides robust error-handling capabilities through the use of the try...catchstatement.

This construct allows developers to handle errors gracefully, ensuring that applications remain functional and user-friendly even when unexpected issues arise.

By default, if a code exception occurs because of a problem in your JavaScript, the script fails and does not finish loading.

This is not usually the desired behavior; in fact, it is often catastrophic.

To prevent these types of problems, wrap your code in a tryand catchblock.

The Basics of try and catch

A try...catchstatement consists of two main blocks: the tryblock and the catchblock.

The tryblock contains code that might throw an error, while the catchblock contains code that executes if an error occurs in the tryblock.

This separation allows you to manage errors without crashing the entire application.

Syntax:


try{ 
  // Code that may throw an error
}catch(error){
  // Code to handle the error
}
            

Example:

// Try-catch block
try{ 
  // Code that might throw an error
  let result = riskyFunction();
  console.log(result);
}catch(error){
  console.log("An error occurred: "+ error.message);
}
            

In the above example, riskyFunction()is called within the tryblock.

If it throws an error, the catchblock logs the error message.

Example

// Try-catch block
try{ 
  // Code that might throw an error
  let result = riskyFunction();
  console.log(result);
}catch(error){
  console.log("An error occurred: "+ error.message);
}

Handling Specific Errors

The catchblock can be used to handle specific errors based on the error message or type.

By inspecting the error object, developers can implement more refined error-handling logic.

Example:

// Try-catch block
try{ 
  // Code that might throw an error
  let data = JSON.parse("invalid JSON");
}catch(error){
  if (error instanceof SyntaxError){ 
    console.log("Invalid JSON format: "+ error.message);
  }else {
    console.log("An unexpected error occurred: "+ error.message);
  }
}
            

Here, the code attempts to parse an invalid JSON string.

If a SyntaxErroroccurs, a specific message is logged. Otherwise, a general error message is displayed.

Example

// Try-catch block
try{ 
  // Code that might throw an error
  let data = JSON.parse("invalid JSON");
}catch(error){
  if (error instanceof SyntaxError){ 
    console.log("Invalid JSON format: "+ error.message);
  }else {
    console.log("An unexpected error occurred: "+ error.message);
  }
}

Using finally with try and catch

The finallyblock can be added to a try...catchstatement to execute code regardless of whether an error was thrown.

This is useful for cleanup operations or releasing resources.

Syntax:


try{ 
  // Code that may throw an error
}catch(error){
  // Code to handle the error
}catch(error){
  // Code that will always run
}
            

Example:


try{ 
  let data = openFile("myFile.txt");
  // Perform operations on the file
}catch(error){
   console.log("Failed to open file: "+ error.message);
}finally{
  console.log("File closed");
}
            

In the above example, finallyblock ensures that the file is closed whether an error occurs or not.

Example


try{ 
  let data = openFile("myFile.txt");
  // Perform operations on the file
}catch(error){
    console.log("Failed to open file: "+ error.message);
}finally{
  console.log("File closed");
}

Nested try...catch Statements

In complex applications, it may be necessary to nest try...catchstatements to handle different layers of errors.

This approach allows for localized error handling and greater control over error management.

Example:


try{ 
  try{ 
    let response = fetchDataFromAPI();
  }catch(networkError){
    console.log("Network error: "+ networkError.message);
  }
  // Additional code that may throw other types of errors
}catch(error){
  console.log("An error occurred: "+ networkError.message);
}
            

In the above example, network errors are handled in the inner catchblock, while other errors are caught by the outer catchblock.

The try...catch statement is a powerful tool for error handling in JavaScript, allowing developers to manage errors gracefully and maintain the stability of their applications.

Example


try{ 
  try{ 
    let response = fetchDataFromAPI();
  }catch(networkError){
    console.log("Network error: "+ networkError.message);
  }
  // Additional code that may throw other types of errors
}catch(error){
  console.log("An error occurred: "+ networkError.message);
}

Let's learn about custom error using in the next chapter.