Skip to content

Error Handling

In JavaScript, an error stops code execution.
Without handling, the application can crash unexpectedly.

➡ With try...catch, we intercept errors to handle them gracefully, preventing application crashes.


  • try → contains code to execute.
  • catch → intercepts errors if they occur.
  • finally → always runs (whether an error occurred or not).
try {
let result = 10 / 0;
console.log(result);
throw new Error("Custom error");
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("Finally block executed");
}

With throw, you can manually throw an error.

function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (e) {
console.error(e.message); // Division by zero is not allowed
}

You can create your own error classes to distinguish cases.

class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 18) {
throw new ValidationError("Age is below the allowed limit");
}
return true;
}
try {
validateAge(15);
} catch (e) {
if (e instanceof ValidationError) {
console.error("Validation error:", e.message);
} else {
console.error("Other error:", e);
}
}

  • Always provide a clear message when throwing errors (throw new Error("...")).
  • Use finally to release resources (close file, terminate connection…).
  • Create custom error types to better categorize issues.
  • Do not overuse try/catch → use them only where an error is likely.