Use and format multiple try-catch blocks in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
4 min

banner

# Table of Contents

  1. Use and format multiple try-catch blocks in JavaScript
  2. Using an if/else statement to handle different errors
  3. Using a nested try/catch statement

# Use and format multiple try-catch blocks in JavaScript

The simplest way to use and format multiple try-catch blocks is to use a separate try/catch for each potential error.

If an error occurs in the try block, it gets passed to the catch() function.

index.js
const throwError = message => { throw new Error(message); }; try { throwError('Error message 1 ๐Ÿ”ด'); } catch (err) { console.log(err); console.log(err.message); // ๐Ÿ‘‰๏ธ Error message 1 ๐Ÿ”ด } try { throwError('Error message 2 ๐Ÿ”ต'); } catch (err) { console.log(err); console.log(err.message); // ๐Ÿ‘‰๏ธ Error message 2 ๐Ÿ”ต }

multiple try catch blocks one after the other

The code for this article is available on GitHub

The throwError function takes a message and throws an error with the supplied message.

If an error is raised in the try block of a try/catch statement, it gets passed to the catch() function.

The code sample above uses a separate try/catch statement to handle each error.

Using multiple try/catch blocks is useful when you need to handle different errors that may occur differently.

# Using an if/else statement to handle different errors

If you need to check if a specific error occurred, you can use an if/else if/else statement in your catch block.

index.js
function ServerException(message) { this.message = message; this.name = 'ServerException'; this.status = 500; } try { throw new ServerException('Server error occurred ๐Ÿ”ด'); } catch (err) { console.log(err); if (err.status === 500) { // ๐Ÿ‘‡๏ธ this runs console.log(`A server error occurred ${err.message}`); } else { console.log(`A generic error occurred ${err.message}`); } }

using if else statement to handle different errors

The code for this article is available on GitHub

We created a ServerException function that takes a message as a parameter and constructs an error object.

Make sure to use a named function and not an arrow function when defining ServerException because we used the this keyword.

The code in the try block throws an error that is then passed to the catch() function.

We check for the status of the error and if its status is 500, then we know that a ServerException has been raised.

Otherwise, a generic error occurred in the try block.

Note that you can also use the instanceof() operator to check if a specific error occurs.

index.js
function ServerException(message) { this.message = message; this.name = 'ServerException'; this.status = 500; } try { throw new ServerException('Server error occurred ๐Ÿ”ด'); } catch (err) { console.log(err); if (err instanceof ServerException) { // ๐Ÿ‘‡๏ธ this runs console.log(`A server error occurred ${err.message}`); } else { console.log(`A generic error occurred ${err.message}`); } }
The code for this article is available on GitHub

The code sample uses the instanceof operator to check if the thrown error is an instance of ServerException.

When using this approach, you don't have to use multiple try/catch statements to handle each error.

Instead, you check what type of error was thrown in the try block.

You can use this approach to check for as many error types as necessary.

index.js
function ServerException(message) { this.message = message; this.name = 'ServerException'; this.status = 500; } function NotFoundException(message) { this.message = message; this.name = 'NotFoundException'; this.status = 404; } try { throw new NotFoundException('Page not found'); } catch (err) { console.log(err); if (err.status === 500) { console.log(`A server error occurred ${err.message}`); } else if (err.status === 404) { // ๐Ÿ‘‡๏ธ this runs console.log(`A 404 not found error occurred ${err.message}`); } else { console.log(`A generic error occurred ${err.message}`); } }
The code for this article is available on GitHub

The else if block runs because the status value of the thrown in the try block error is 404.

And here is the equivalent example, but using the instanceof operator.

index.js
function ServerException(message) { this.message = message; this.name = 'ServerException'; this.status = 500; } function NotFoundException(message) { this.message = message; this.name = 'NotFoundException'; this.status = 404; } try { throw new NotFoundException('Page not found'); } catch (err) { console.log(err); if (err instanceof ServerException) { console.log(`A server error occurred ${err.message}`); } else if (err instanceof NotFoundException) { // ๐Ÿ‘‡๏ธ this runs console.log(`A 404 not found error occurred ${err.message}`); } else { console.log(`A generic error occurred ${err.message}`); } }
The code for this article is available on GitHub

The if statement checks if the thrown error is an instance of ServerException.

The else if statement checks if the error is an instance of NotFoundException.

If none of the conditions is met, the else block runs.

# Using a nested try/catch statement

If you need to handle a specific error differently, you can also use a nested try/catch statement.

index.js
try { console.log('Some code that maybe throws'); try { console.log( 'Some code that might throw and needs to be handled differently', ); } catch (nestedErr) { console.log('Nested catch error: ', nestedErr.message); } } catch (err) { console.log('Outer catch error: ', err.message); }

using nested try catch statement

The code for this article is available on GitHub

The outer try statement should contain code that might or might not throw an exception.

The outer catch is used to handle the generic error.

The nested try/catch statement is used to handle a specific error.

The nested try block should contain code that might throw a specific exception that you need to handle differently.

If the code in the nested try throws an error, the error gets passed to the nested catch() function.

I've also written an article on how to convert an error object to a string in JavaScript.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev