🟨 JavaScript Intermediate

What is error handling in JavaScript?

Answer

JavaScript uses try/catch/finally for synchronous error handling and Promise rejections for asynchronous. try { riskyOperation(); } catch(error) { console.error(error.message, error.stack); } finally { cleanup(); }. The finally block always runs. Custom errors: extend the Error class: class ValidationError extends Error { constructor(message, field) { super(message); this.name = "ValidationError"; this.field = field; } }. Check error type: error instanceof ValidationError. Async error handling: try { await fetchData(); } catch(err) { ... } or promise.catch(err => { ... }). Global error handlers: window.addEventListener("error", handler) for uncaught synchronous errors, window.addEventListener("unhandledrejection", handler) for unhandled Promise rejections. Error types: SyntaxError, ReferenceError, TypeError, RangeError, URIError, EvalError. Always handle Promise rejections — unhandled rejections crash Node.js processes.