No announcement
 

Try-Catch Statement

Error handling is a crucial aspect of writing robust and reliable JavaScript code. It allows you to gracefully handle unexpected situations or errors that may occur during the execution of your code.

Example:

error_handling.html

<!DOCTYPE html>
<html>
<head>
  <title>Error Handling Example</title>
</head>
<body>

<h2>Error Handling:</h2>
<button id="btn">Divide Numbers</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
  try {
    let numerator = parseFloat(prompt("Enter numerator:"));
    let denominator = parseFloat(prompt("Enter denominator:"));

    if (isNaN(numerator) || isNaN(denominator) || denominator === 0) {
      throw new Error("Invalid input or division by zero.");
    }

    let result = numerator / denominator;
    document.getElementById("output").textContent = "Result: " + result;
  } catch (error) {
    document.getElementById("output").textContent = "Error: " + error.message;
  }
});
</script>

</body>
</html>

Output
When you click the "Divide Numbers" button, a series of prompts will appear asking for the numerator and denominator. If you enter invalid input or try to divide by zero, an error message will be displayed. Otherwise, the result of the division will be shown.

Explanation:

  • In this example, a button with the id "btn" and an empty <p> element with the id "output" are defined in the HTML.
  • When the "Divide Numbers" button is clicked, an event listener triggers an operation inside a try block.
  • Inside the try block, we parse the user input into numbers. If the input is not a number or if the denominator is 0, we throw a new Error object with a custom error message.
  • If no errors occur, the division is performed, and the result is displayed in the <p> element with the id "output".
  • If an error occurs, the catch block catches the error, and its error message is displayed in the <p> element.