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");
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>
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
}