Interview Questions
Error Handling · Study material
Error Handling – Interview Questions
1. How does try/catch/finally work?
try runs the code; if it throws, control jumps to catch with the error; finally runs afterwards in every case, even after return, break or a new throw.
2. What happens if finally contains a return?
It overrides any return value or thrown error from try/catch – the original error is silently lost. Avoid control flow in finally.
3. Name the built-in error types.
Error, TypeError, ReferenceError, SyntaxError, RangeError, URIError, EvalError and AggregateError.
4. Can you throw something that is not an Error?
Yes, any value – but you lose the stack trace and type checks, so always throw Error objects (or subclasses).
5. How do you create a custom error?
class MyError extends Error { constructor(msg, extra) { super(msg); this.name = "MyError"; this.extra = extra; } }
6. What is error.cause?
An ES2022 option, new Error(message, { cause }), that attaches the underlying error when you wrap it.
7. Why can't try/catch catch an error inside setTimeout?
The callback runs later on a new call stack, after the try block has finished. Put the try/catch inside the callback.
8. How do you handle errors in async/await?
Wrap awaits in try/catch, or call .catch on the returned promise. Promise.allSettled collects multiple outcomes.
9. What is an unhandled promise rejection?
A rejected promise with no handler. Node.js terminates by default; browsers log it and fire unhandledrejection.
10. What is optional catch binding?
catch { … } without (e) – allowed since ES2019 when you do not need the error object.
11. Is a SyntaxError catchable?
Only when it happens at run time (JSON.parse, new Function, eval). A syntax error in the script itself stops it from running at all.
12. Why should you not swallow errors?
An empty catch hides failures, so the program continues with bad data and the real cause becomes hard to find.
13. What is AggregateError?
An error holding several errors in its errors array; Promise.any rejects with it, and you can throw it for multi-field validation.
14. How do you check an error's type?
instanceof (works with subclasses), or the name property when errors cross realms or come from serialised data.
15. Exceptions vs returned errors – when to use which?
Throw for unexpected failures and bugs; return a result (null, default, [err, value]) when failure is an ordinary, expected outcome.