Error Handling: try/catch/throw
8 min read
Error Handling
Errors are inevitable. Handling them gracefully — logging useful information, recovering where possible, and failing clearly — is the mark of production-ready code.
javascript
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
// `error` is an Error object with .message and .stack
console.error("Something went wrong:", error.message);
} finally {
// Always runs — use for cleanup (close files, stop spinners)
cleanup();
}Throwing Errors
javascript
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
// Custom error classes
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email", "Invalid format");
} catch (e) {
if (e instanceof ValidationError) {
console.log(e.field, e.message); // email Invalid format
} else {
throw e; // re-throw unexpected errors
}
}Always re-throw errors you do not know how to handle. A caught-and-swallowed error is worse than a crash — it hides bugs and makes debugging nearly impossible.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises