Error Handling with Try-Catch:

 Error Handling with Try-Catch:


Error handling is an essential aspect of programming. JavaScript provides the try-catch statement to handle and manage exceptions.



function divide(a, b) {

  try {

    if (b === 0) {

      throw new Error('Division by zero is not allowed.');

    }

    return a / b;

  } catch (error) {

    console.error(error.message);

  }

}


console.log(divide(10, 0)); // Output: Division by zero is not allowed.

In the example above, the divide function attempts to perform a division operation. If the divisor (b) is zero, an Error object is thrown using the throw statement. The thrown error is then caught by the catch block, and the error message is logged to the console.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...