No announcement
 

Throwing Custom Errors

You can throw custom error objects to provide more context and information about the error.

Example:

custom_error.html

<!DOCTYPE html>
<html>
<head>
  <title>Throwing Custom Errors Example</title>
</head>
<body>

<h2>Throwing Custom Errors:</h2>
<button id="btn">Calculate Age</button>
<p id="output"></p>

<script>
document.getElementById("btn").addEventListener("click", function() {
  try {
    let birthYear = parseInt(prompt("Enter birth year:"));

    if (isNaN(birthYear)) {
      throw new CustomError("Invalid input: Please enter a valid year.");
    }

    let currentYear = new Date().getFullYear();
    let age = currentYear - birthYear;
    document.getElementById("output").textContent = "Your age: " + age;
  } catch (error) {
    document.getElementById("output").textContent = "Error: " + error.message;
  }
});

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  }
}
</script>

</body>
</html>

Output
When you click the "Calculate Age" button, a prompt will appear asking for the birth year. If you enter invalid input, a custom error message will be displayed. Otherwise, your age will be calculated and shown.

Explanation:

  • Similar to the previous example, this example contains a button and an empty <p> element in the HTML.
  • When the "Calculate Age" button is clicked, an event listener triggers an operation inside a try block.
  • Inside the try block, we parse the user input into a number. If the input is not a number, we throw a custom error by creating a CustomError object with a custom error message.
  • If no errors occur, the age is calculated and displayed.
  • The CustomError class is defined using ES6 class syntax. It extends the built-in Error class and provides a custom name and message for the error.

Proper error handling is vital to ensure that your JavaScript code is resilient and user-friendly. By using the try-catch statement and creating custom error classes, you can effectively manage errors and provide meaningful feedback to users.