45. How do you perform exception handling in JavaScript?
medium
Exception handling is an essential part of any programming language that allows developers to gracefully handle errors and exceptions that occur during program execution. In JavaScript, there are several ways to handle exceptions, but the most commonly used method is try-catch blocks.

A try-catch block is a pair of statements in which the first statement (try) contains the code that might throw an exception, and the second statement (catch) specifies what to do when an exception occurs. Here's an example:
try {
  // Code that might throw an exception
  const result = 10 / 0;
} catch (error) {
  // Code to handle the exception
  console.log("An error occurred:", error);
}

In this example, we're attempting to divide 10 by 0, which will throw a TypeError because division by zero is not allowed. We wrap this code in a try-catch block to handle the exception that might occur. When an exception occurs, it will be caught by the catch statement, and the code inside the catch block will execute.
Another way to handle exceptions in JavaScript is through global error handling using the window.onerror event. This event fires when an unhandled exception occurs anywhere in the browser. Here's an example:
window.onerror = function(message, source, lineNumber, columnNumber) {
  // Code to handle the exception
  console.log("An error occurred:", message);
};

In this example, we're setting up a global error handler that will catch any unhandled exceptions in the browser and log them to the console.

In conclusion, JavaScript provides several ways to handle exceptions, but the most commonly used method is try-catch blocks. These allow developers to gracefully handle errors and exceptions that occur during program execution, ensuring that their code runs smoothly and efficiently.