JavaScript Error Handling

1. What is Error Handling?

No matter how good you are at programming, scripts can contain errors. They may occur because of mistakes, unexpected user input, or erroneous server responses.

By default, if an error occurs, JavaScript stops execution and prints the error to the console. Error handling allows you to catch these errors and execute alternative code (like showing a friendly message) instead of crashing the application.

2. The `try...catch` Statement

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed if an error occurs in the try block.

try {
    // Code that might fail
    let result = someUndefinedFunction(); 
    document.write("This will not run");
} catch (error) {
    // Code to handle the error
    document.write("An error occurred: " + error.message);
}
        
Output will appear here...

3. The `finally` Block

The finally statement lets you execute code, after try and catch, regardless of the result. This is useful for cleanup tasks (like closing a file or hiding a loading spinner).

try {
    document.write("Trying...");
    throw new Error("Something went wrong!");
} catch (error) {
    document.write("Caught: " + error.message);
} finally {
    document.write("Finally: This runs no matter what.");
}
        
Output will appear here...

4. The `throw` Statement

The throw statement allows you to create a custom error. You can throw a string, a number, a boolean, or an object.

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero!");
    }
    return a / b;
}

try {
    document.write(divide(10, 0));
} catch (e) {
    console.error("Error:", e.message);
}
        
Output will appear here...

5. Real World Example: Input Validation

Try entering a value below. If it's empty, not a number, or too low/high, an error will be thrown and caught.

let ageInput = document.getElementById("ageInput");
let checkBtn = document.getElementById("checkBtn");
let errorOutput = document.getElementById("errorOutput");

checkBtn.addEventListener("click", function() {
    try {
        errorOutput.textContent = ""; // Clear previous message
        let age = Number(ageInput.value);
        
        if(ageInput.value.trim() == "") throw new Error("Input is empty");
        if(isNaN(age)) throw new Error("Please enter a valid number");
        if(age < 18) throw new Error("You must be 18 or older");
        if(age > 100) throw new Error("Age is too high");
        
        errorOutput.textContent = "Access Granted";
        errorOutput.style.color = "green";
    } catch(e) {
        errorOutput.textContent = e.message;
        errorOutput.style.color = "red";
    }
});
        

6. Comparison Table

Feature Description
try Block of code to test for errors.
catch Block of code to execute if an error occurs.
throw Create custom error messages.
finally Block of code that runs regardless of the result.
Best Practice: Always throw meaningful error messages (using new Error("message")) and handle them using try...catch to prevent your application from crashing unexpectedly.

Practice Questions

Test your understanding of JavaScript Error Handling.

Easy

Q1: Use try...catch to handle errors.

  • Write a try block containing code that parses an invalid JSON string (e.g., "{ invalid json }").
  • Write a catch block to handle the potential error.
  • Inside the catch block, log a custom error message to the console.
Easy

Q2: Access the error object.

  • Create a try...catch block.
  • Inside the try block, intentionally call an undefined function to trigger an error.
  • Inside the catch block, log the message property of the error object to the console.
Medium

Q3: Use the finally block.

  • Explain the purpose of the finally block.
  • Write a try...catch...finally structure.
  • Log a message inside the finally block to show it runs regardless of an error.
Medium

Q4: Throw a custom error.

  • Write a function named checkInput that takes a value.
  • Check if the value is empty or falsy.
  • If empty, manually throw a new Error with the message "Invalid input!".
Hard

Q5: Validate input and handle custom errors.

  • Write a function checkPositive(num).
  • Throw an Error with the message "Number must be positive!" if the number is less than 0.
  • Call this function with a negative number inside a try block.
  • Handle the error in the catch block and log the error message.

Answer

Code: