JavaScript Catch Expression

What is Catch Expression in JavaScript?

In JavaScript, the catch block serves the purpose of managing errors that may occur in the code by executing a specific series of statements defined within the block. By utilizing the catch expression, we can encapsulate either a custom exception handler created by the user or a pre-existing built-in handler.

The catch expression is responsible for executing only those segments of code within the try block that are susceptible to errors and require handling. By utilizing the catch expression, we can establish a code segment that will run when an error is encountered in the try block.

It is utilized for managing errors that may arise within the program. In the event that an error is encountered within the try {} block, the JavaScript runtime engine proceeds to execute the code contained within the catch{} block to effectively address the issue.

Within the catch{} statement, two distinct types of handlers may exist. The first type is known as the exceptional handler, while the second is referred to as the built-in handler. In JavaScript, the execution of the catch block occurs solely when an error arises within the try block, indicating that the error requires resolution.

Syntax

Example

try {

    // Try block

} catch (exception variable) {

    // Catch block

}

Note: In JavaScript, the catch{} statement executes only after the execution of the try{} statement. Also, one try block can contain one or more catch blocks.

Conditional Catch Expression

In JavaScript, within the catch block, it is possible to utilize the if-else construct to manage errors based on specific conditions. This approach allows us to employ a single catch{} statement to address errors arising from multiple try {} statements.

Within the catch block, it is possible to determine the error type by utilizing the instanceOf operator, allowing us to manage the error based on its specific type.

Example

Example

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    <div id="Hello"></div>

    <script>

        const output = document.getElementById("Hello");

        try{

            welcome(); //function is not defined

        } catch (a) {

            if (a instanceof ReferenceError){

                output.innerHTML= "Reference error is occurred";

            } else if (a instanceof TypeError) {

                output.innerHTML = "Type error is occurred";

            }else if (a instanceof RangeError){

                output.innerHTML = "Range error is occurred";

            } else if (a instanceof SyntaxError) {

                output.innerHTML = "Syntax error is occurred";

            } else {

                output.innerHTML = "Error is occurred";

            }

        }

    </script>

</body>

</html>

Output:

Optional Catch Binding

In JavaScript, the optional catch binding is a feature utilized for handling the error argument. This capability was introduced in ES10, also known as ECMAScript 2019. Within a try-catch statement, when an error occurs and there is no need to process that error, the optional catch binding allows us to bypass the handling of it.

Syntax:

Example

// try...catch with error argument

try{

} catch(err) {   // error argument 

}

// try...catch without error argument

try{

} catch{   // Skipped the Error argument

}

Example

Example

let json;

      try{

          json = JSON.parse('abcd')

      }catch{    // Skipped the error argument 

          console.log("It is a JSON parse exception ")

          json = {};

      }

      console.log(json)

Output:

Output

It is a JSON parse exception 

{}

Why do we use the Catch Expression in JavaScript?

There are several justifications for utilizing the catch expression in JavaScript. These reasons include the following:

Error Handling

In JavaScript, when an error arises within the try block, we can effectively manage the error using the catch statement. This approach prevents the error from propagating, which could adversely impact user experience and compromise the integrity of our code.

Recovery

The catch expression plays a crucial role in managing errors by facilitating recovery and offering an alternative route for your program in the event of unexpected occurrences. This may involve recording the error and displaying a message that is easy for users to understand, or it may initiate a remedial action to address the issue.

Debugging

In JavaScript, the catch statement offers a way to log error details, which assists us in troubleshooting problems that may arise during execution.

Example

Example

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

</head>

<body>

    <div id = "demo"> </div>

   <script>

      const output = document.getElementById("demo");

      try {

         output.innerHTML += "In the start of try block <br>";

         welcome();

         output.innerHTML += "In the end of try block <br>";

      } catch (err) {

         output.innerHTML += "In the catch block <br>";

         output.innerHTML += "The error name is: " + err.name + "<br>";

         output.innerHTML += "The error message is: " + err.message + ".<br>";

      }

   </script>

</body>

</html>

Output:

Example 2

Example

// Define a function to perform a series of operations that may throw errors

function processData(data) {

    try {

      // Step 1: Validate the data

      if (!data || typeof data !== 'object') {

        throw new Error('Invalid data format');

      }

  

      // Step 2: Extract the necessary fields from the data

      const { name, age, occupation } = data;

      if (!name || !age || !occupation) {

        throw new Error('Missing required fields');

      }

  

      // Step 3: Perform some calculations on the data

      const salary = calculateSalary(occupation);

      if (salary < 0) {

        throw new Error('Invalid salary calculation');

      }

  

     // Step 4: Save the data to a database

      try {

        saveToDatabase(data);

      } catch (error) {

        // Catch any errors that occur during database saving

        console.error('Error saving to database:', error.message);

        throw error; // Rethrow the error to be caught by the outer catch block

      }

       // If we reach this point, the data was processed successfully

      console.log('Data processed successfully!');

    } catch (error) {

      // Catch any errors that occur during the processing steps

      if (error instanceof SyntaxError) {

        console.error('Syntax error:', error.message);

      } else if (error instanceof TypeError) {

        console.error('Type error:', error.message);

      } else {

        console.error('Unknown error:', error.message);

      }

    }

  }

  

  // Define a function to calculate the salary based on occupation

  function calculateSalary(occupation) {

    try {

      switch (occupation) {

        case 'Software Engineer':

          return 100000;

        case 'Doctor':

          return 200000;

        case 'Lawyer':

          return 150000;

        default:

          throw new Error('Unknown occupation');

      }

    } catch (error) {

      // Catch any errors that occur during salary calculation

      console.error('Error calculating salary:', error.message);

      throw error; // Rethrow the error to be caught by the outer catch block

    }

  }

  

  // Define a function to save the data to a database

  function saveToDatabase(data) {

    try {

      // Simulate a database connection and saving the data

      console.log('Saving data to database...');

      setTimeout(() => {

        console.log('Data saved successfully!');

      }, 2000);

    } catch (error) {

      // Catch any errors that occur during database saving

      console.error('Error saving to database:', error.message);

      throw error; // Rethrow the error to be caught by the outer catch block

    }

  }

  

  // Test the program with different inputs

  processData({ name: 'John', age: 30, occupation: 'Software Engineer' });

  processData({ name: 'Jane', age: 25, occupation: 'Doctor' });

  processData({ name: 'Bob', age: 40, occupation: 'Lawyer' });

  processData({ name: 'Alice', age: 35, occupation: 'Unknown' });

  processData({}); // Invalid data format

  processData(null); // Invalid data format

Output:

Output

Saving data to database...

Data processed successfully!

Saving data to database...

Data processed successfully!

Saving data to database...

Data processed successfully!

Error calculating salary: Unknown occupation

Unknown error: Unknown occupation

Unknown error: Missing required fields

Unknown error: Invalid data format

Data saved successfully!

Data saved successfully!

Data saved successfully!

Advantages of using Catch Expression in JavaScript

Utilizing the catch expression in JavaScript offers several benefits. These include:

Debugging and Logging

Error Logging: In JavaScript, it is possible to record errors in the console or send them to an external logging service, facilitating the user's ability to monitor and troubleshoot problems that arise in a production environment.

In JavaScript, when we handle exceptions, we can readily retrieve error information that helps us comprehend what occurred and the location of the issue.

Control Flow Management

Fallback strategy: By utilizing the catch expression in JavaScript, we can establish a fallback strategy or alternative logic that activates in the event of an error. This approach ensures that our application continues to operate effectively, even when encountering unforeseen issues.

Resource cleanup: This process guarantees that resources are adequately released, even in the event of an error, thereby preventing any potential resource leaks.

Separation of Concerns

Error segregation: In JavaScript, we have the capability to distinguish the error-handling processes from the standard code, facilitating a cleaner and more organized codebase. This distinction enables us to concentrate on the main logic, while the error management is addressed independently.

Asynchronous Error Handling

Promises and Async/Await: In JavaScript, when dealing with asynchronous programming constructs like Promises or the async/await syntax, the catch method plays a crucial role in managing rejections or exceptions that may arise during asynchronous tasks. This practice guarantees that errors are effectively handled within an asynchronous environment.

Custom Error Handling

Custom error types: In JavaScript, it is possible to throw and catch custom error types, enabling us to manage specific situations with greater precision. This approach facilitates more detailed error handling tailored to various error categories.

Input Required

This code uses input(). Please provide values below: