No announcement

Throwing Custom Errors

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



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

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

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); = "CustomError";


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.


  • 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.