Error Handling

try…catch

console.log("This is the start of the program");
try{
    console.log(a);
}
catch(err){
    console.log("The Error is: "+err);
}
console.log("This is the end of the program");

Throwing Errors

try {
    let a = 9 / 0;
    console.log(a); // Infinity
    if (!isFinite(a)) {
        throw new Error("Division by zero");
    }
} catch (error) {
    console.log(error.message); // Division by zero
}

<aside> 💡 JavaScript errors are objects with a base class of Error, including SyntaxError, ReferenceError, TypeError, etc., and custom errors can extend Error for specialized handling.

</aside>

throw Custom Error Objects

class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = "CustomError";
    }
}
try {
    throw new CustomError("Something went wrong");
} 
catch (error) {
    console.error(error.name); // Output: CustomError
    console.error(error.message); // Output: Something went wrong
}

Throwing Custom Errors with throw

The throw statement allows you to create custom error messages or throw exceptions explicitly. You can throw any type of object, but it's common to throw an instance of the Error object

function checkAge(age) {
    if (age < 18) {
        throw new Error("You must be at least 18 years old.");
    } else {
        console.log("Age is valid");
    }
}

try {
    checkAge(15);  // This will throw an error
} catch (error) {
    console.log(error.message);  // Output: You must be at least 18 years old.
}