JavaScript Error Handling MCQs for Developer Interviews & Certification

1 min read

Exception and error handling in JavaScript is essential for preventing runtime crashes and maintaining application stability across complex web environments. Using control structures like try...catch...finally, developers can gracefully intercept unexpected errors, inspect native error subclasses (TypeError, ReferenceError, SyntaxError, RangeError), and define custom exception classes. Modern JavaScript applications also require robust asynchronous error management using promise catch chains or try...catch blocks with async/await. Understanding how error boundaries, stack traces, and global unhandled rejection events operate is vital for writing resilient code and succeeding in technical software engineering interviews.

1. What is the primary keyword construct used to handle runtime exceptions synchronously in JavaScript?

a) try...catch...finally
b) protect...rescue...ensure
c) monitor...handle...release
d) begin...except...end
Correct Answer: a) try...catch...finally
Explanation:
JavaScript uses the standard try...catch...finally block structure to gracefully catch and handle runtime exceptions.

2. What happens when an exception is thrown inside a 'try' block?

a) Execution immediately jumps to the matching 'catch' block, bypassing the remainder of the 'try' block.
b) The entire script crashes and terminates execution immediately.
c) The browser reloads automatically.
d) Execution pauses until the user clicks resume.
Correct Answer: a) Execution immediately jumps to the matching 'catch' block, bypassing the remainder of the 'try' block.
Explanation:
Throwing an error breaks normal execution flow in the try block and transfers control directly to the catch clause.

3. Which built-in JavaScript object represents a runtime error and is typically thrown as an exception?

a) Error
b) Exception
c) Fault
d) Failure
Correct Answer: a) Error
Explanation:
The global Error constructor creates error objects that contain a message and stack trace when thrown.

4. What is the purpose of the 'finally' block in exception handling?

a) To execute cleanup code regardless of whether an exception was thrown or caught in the try/catch blocks.
b) To catch uncaught asynchronous errors.
c) To define fallback return values when catch fails.
d) To force garbage collection of error objects.
Correct Answer: a) To execute cleanup code regardless of whether an exception was thrown or caught in the try/catch blocks.
Explanation:
The finally block always runs after try and catch execution complete, making it ideal for resource cleanup.

5. Can you use a 'try' block without either a 'catch' block or a 'finally' block?

a) No, a try block must be accompanied by at least a catch block, a finally block, or both.
b) Yes, try blocks can stand completely alone.
c) Yes, but only in non-strict mode.
d) Yes, if wrapped inside an arrow function.
Correct Answer: a) No, a try block must be accompanied by at least a catch block, a finally block, or both.
Explanation:
Syntax rules require every try statement to have either a catch block, a finally block, or both.

6. What is a SyntaxError in JavaScript?

a) An error thrown when the parser encounters code that violates JavaScript syntax rules during compilation/parsing before execution.
b) An error thrown when a variable is reassigned.
c) An error thrown when network requests fail.
d) An error thrown when stack overflow occurs.
Correct Answer: a) An error thrown when the parser encounters code that violates JavaScript syntax rules during compilation/parsing before execution.
Explanation:
Syntax errors occur during parsing before any code runs, preventing the script from executing entirely.

7. What is a ReferenceError in JavaScript?

a) An error thrown when attempting to reference an undeclared identifier or a variable residing in the Temporal Dead Zone.
b) An error thrown when passing an invalid argument type to a function.
c) An error thrown when JSON parsing fails.
d) An error thrown when memory limits are exceeded.
Correct Answer: a) An error thrown when attempting to reference an undeclared identifier or a variable residing in the Temporal Dead Zone.
Explanation:
ReferenceError occurs when evaluating an invalid identifier reference.

8. What is a TypeError in JavaScript?

a) An error thrown when a value is not of the expected type, such as invoking a non-function or reading properties of undefined/null.
b) An error thrown during network timeouts.
c) An error thrown when regular expressions fail to match.
d) An error thrown when arithmetic overflow occurs.
Correct Answer: a) An error thrown when a value is not of the expected type, such as invoking a non-function or reading properties of undefined/null.
Explanation:
TypeError arises when an operation is performed on an incompatible data type.

9. What is a RangeError in JavaScript?

a) An error thrown when a numeric value is outside an allowable range (e.g., invalid array lengths or recursive stack overflow).
b) An error thrown when array indices are negative.
c) An error thrown when CSS pixel limits are breached.
d) An error thrown during string concatenation.
Correct Answer: a) An error thrown when a numeric value is outside an allowable range (e.g., invalid array lengths or recursive stack overflow).
Explanation:
RangeError indicates parameters exceeding permissible numeric boundaries.

10. How do you create a custom error class in modern JavaScript?

a) By extending the built-in Error class (`class CustomError extends Error {}`)
b) By creating a standard object literal with an error flag
c) Using the `new Exception()` keyword
d) By overriding the global console object
Correct Answer: a) By extending the built-in Error class (`class CustomError extends Error {}`)
Explanation:
Extending the base Error class preserves stack traces and proper prototype inheritance for custom errors.

11. What is the purpose of passing a message string to `new Error('message')`?

a) It sets the error's `.message` property, describing the nature of the failure for debugging purposes.
b) It triggers an immediate console log alert.
c) It sends a network notification to the server.
d) It overrides the stack trace completely.
Correct Answer: a) It sets the error's `.message` property, describing the nature of the failure for debugging purposes.
Explanation:
The error message provides human-readable context stored on the error instance.

12. What does the `.stack` property on an Error object contain?

a) A string representing the call stack trace at the exact moment the error was instantiated
b) An array of all active try/catch block references
c) The execution queue of asynchronous microtasks
d) The memory address where the error occurred
Correct Answer: a) A string representing the call stack trace at the exact moment the error was instantiated
Explanation:
The stack property records function call paths leading up to the error creation.

13. Can synchronous `try...catch` blocks catch errors thrown inside asynchronous callbacks (e.g., inside `setTimeout`)?

a) No, because asynchronous callbacks execute in a later event loop tick outside the synchronous try/catch execution context.
b) Yes, try/catch automatically wraps all async timers.
c) Yes, if strict mode is enabled.
d) Only if using arrow functions.
Correct Answer: a) No, because asynchronous callbacks execute in a later event loop tick outside the synchronous try/catch execution context.
Explanation:
Synchronous try/catch blocks cannot catch errors thrown inside macrotasks like setTimeout since the try block has already finished executing.

14. How do you handle errors thrown inside Promise chains?

a) By appending a `.catch()` error handler to the Promise chain or using `try...catch` with `async/await`.
b) Using standard synchronous try/catch blocks directly around the promise creation.
c) By setting `window.onerror` handlers.
d) Promises cannot throw errors.
Correct Answer: a) By appending a `.catch()` error handler to the Promise chain or using `try...catch` with `async/await`.
Explanation:
Promise rejections propagate down the chain until caught by `.catch()` or handled via `try...catch` with async/await.

15. How does `try...catch` behave with `async/await` syntax?

a) A `try...catch` block surrounding `await` expressions successfully catches rejected promises and thrown asynchronous errors.
b) It fails to catch rejected promises because async code requires `.catch()`.
c) It causes a syntax exception.
d) It converts async code into synchronous execution.
Correct Answer: a) A `try...catch` block surrounding `await` expressions successfully catches rejected promises and thrown asynchronous errors.
Explanation:
Using `await` transforms promise rejections into synchronous-like exceptions that `try...catch` can catch.

16. What is an unhandled promise rejection?

a) A rejected promise that lacks any `.catch()` error handler or try/catch handling, triggering global warning events in runtimes.
b) An error thrown during JSON serialization.
c) A syntax error in async functions.
d) A network timeout failure.
Correct Answer: a) A rejected promise that lacks any `.catch()` error handler or try/catch handling, triggering global warning events in runtimes.
Explanation:
Unhandled rejections occur when promises fail without any error consumers attached.

17. Which global event listener catches unhandled promise rejections in browser environments?

a) unhandledrejection
b) error
c) promisefail
d) catcherror
Correct Answer: a) unhandledrejection
Explanation:
The `unhandledrejection` event fires on the window when a promise rejection goes unhandled.

18. Which global event listener catches general uncaught runtime errors in browser environments?

a) error
b) fail
c) exception
d) uncaught
Correct Answer: a) error
Explanation:
The global `error` event on window catches uncaught runtime exceptions.

19. What is the purpose of the `throw` statement?

a) To explicitly generate a user-defined runtime exception halting normal execution flow
b) To throw data into a Web Worker thread
c) To release memory allocated by variables
d) To trigger garbage collection pauses
Correct Answer: a) To explicitly generate a user-defined runtime exception halting normal execution flow
Explanation:
The throw statement interrupts execution and passes an exception value up the call stack.

20. Can you throw primitive values (like strings or numbers) instead of Error objects in JavaScript?

a) Yes, JavaScript permits throwing any expression, though throwing Error objects is strongly recommended for stack traces.
b) No, throwing anything other than an Error instance throws a SyntaxError.
c) Only numbers can be thrown.
d) Only in strict mode.
Correct Answer: a) Yes, JavaScript permits throwing any expression, though throwing Error objects is strongly recommended for stack traces.
Explanation:
While `throw 'error'` works, it lacks stack traces, making Error objects best practice.

21. What happens if an exception is thrown inside a `catch` block?

a) The exception propagates outward to the next enclosing outer try/catch block or crashes the program if unhandled.
b) It is automatically ignored by the engine.
c) It is caught by the same catch block recursively.
d) It converts into a warning.
Correct Answer: a) The exception propagates outward to the next enclosing outer try/catch block or crashes the program if unhandled.
Explanation:
Errors thrown inside catch blocks require nested try/catch blocks or they escape outward.

22. What is the execution order when `return` statements exist inside `try`, `catch`, and `finally` blocks?

a) If a `finally` block contains a `return` statement, it overrides any return values from the `try` or `catch` blocks.
b) The try return value always takes absolute precedence.
c) Return statements inside finally blocks are forbidden.
d) Execution halts without returning anything.
Correct Answer: a) If a `finally` block contains a `return` statement, it overrides any return values from the `try` or `catch` blocks.
Explanation:
A return statement in finally supersedes previous return or throw outcomes from try/catch.

23. What is a URIError in JavaScript?

a) An error thrown when global URI handling functions (`encodeURI()` or `decodeURI()`) receive malformed input parameters.
b) An error thrown when fetch network requests return 404.
c) An error thrown when CSS stylesheet links fail to load.
d) An error thrown during WebSocket handshakes.
Correct Answer: a) An error thrown when global URI handling functions (`encodeURI()` or `decodeURI()`) receive malformed input parameters.
Explanation:
URIError occurs when malformed URI strings are passed to encoding/decoding functions.

24. What is an EvalError in JavaScript?

a) An error thrown regarding the global `eval()` function (though rarely thrown in modern ECMAScript specifications).
b) An error thrown when compiling WebAssembly code.
c) An error thrown during JSON.parse evaluation.
d) An error thrown when mathematical expressions overflow.
Correct Answer: a) An error thrown regarding the global `eval()` function (though rarely thrown in modern ECMAScript specifications).
Explanation:
EvalError relates to eval usage, though modern JS engines rarely throw it directly.

25. Why is using `eval()` generally discouraged in JavaScript regarding security and error handling?

a) It executes arbitrary strings as code, creating severe security vulnerabilities (injection attacks) and complicating debugging and error tracking.
b) It causes infinite recursion stack overflows.
c) It disables garbage collection entirely.
d) It throws uncatchable SyntaxErrors.
Correct Answer: a) It executes arbitrary strings as code, creating severe security vulnerabilities (injection attacks) and complicating debugging and error tracking.
Explanation:
eval introduces security risks and performance penalties, making error tracing difficult.

26. What is defensive programming in the context of error handling?

a) Anticipating potential failure states by validating inputs, checking for null/undefined values, and handling errors before exceptions occur.
b) Wrapping every single line of code in massive try/catch blocks.
c) Disabling strict mode to prevent runtime crashes.
d) Ignoring errors entirely to keep UI responsive.
Correct Answer: a) Anticipating potential failure states by validating inputs, checking for null/undefined values, and handling errors before exceptions occur.
Explanation:
Defensive programming prevents unexpected exceptions through proactive validation.

27. What is the Fail-Fast principle in error handling?

a) Reporting errors immediately when they occur rather than failing silently or propagating invalid state downstream.
b) Restarting the browser every time a warning occurs.
c) Aborting network requests after 100 milliseconds.
d) Catching all errors and returning null silently.
Correct Answer: a) Reporting errors immediately when they occur rather than failing silently or propagating invalid state downstream.
Explanation:
Failing fast surfaces bugs early in development, preventing corrupted data propagation.

28. What is the difference between error handling and error logging?

a) Error handling intercepts exceptions to recover or fail gracefully, whereas error logging records error details to diagnostic storage or consoles for developers.
b) Error logging replaces try/catch blocks entirely.
c) Error handling only works in backend Node.js apps.
d) They are identical processes.
Correct Answer: a) Error handling intercepts exceptions to recover or fail gracefully, whereas error logging records error details to diagnostic storage or consoles for developers.
Explanation:
Handling dictates program flow during failure, while logging records diagnostic data.

29. How does `console.error()` differ from `console.log()` in developer tools?

a) console.error() formats output as an error message (often red with stack traces in some environments) and may output to standard error streams in Node.js.
b) console.error() throws an uncaught exception automatically.
c) console.error() is asynchronous.
d) There is no difference.
Correct Answer: a) console.error() formats output as an error message (often red with stack traces in some environments) and may output to standard error streams in Node.js.
Explanation:
console.error formats diagnostic error logs clearly for developers.

30. What is an AggregateError in JavaScript?

a) An error object representing multiple errors grouped together, commonly thrown by methods like `Promise.any()` when all promises reject.
b) An error thrown when database aggregation queries fail.
c) An error thrown when memory usage crosses aggregate limits.
d) A compilation error thrown by Babel.
Correct Answer: a) An error object representing multiple errors grouped together, commonly thrown by methods like `Promise.any()` when all promises reject.
Explanation:
AggregateError encapsulates multiple errors in an `errors` array property.

31. What does `Promise.allSettled()` do regarding error handling compared to `Promise.all()`?

a) Promise.allSettled waits for all promises to finish regardless of success or failure, whereas Promise.all rejects immediately upon the first failure.
b) Promise.allSettled catches all errors automatically without throwing.
c) Promise.all ignores rejected promises.
d) They behave identically.
Correct Answer: a) Promise.allSettled waits for all promises to finish regardless of success or failure, whereas Promise.all rejects immediately upon the first failure.
Explanation:
allSettled captures outcomes for every promise, while all short-circuits on rejection.

32. How does `try...catch` handle errors thrown inside generator functions?

a) Exceptions thrown inside generators can be caught using `try...catch` around generator execution or iterator `.throw()` calls.
b) Generators cannot throw catchable errors.
c) Generator errors always crash the event loop.
d) Only async generators support try/catch.
Correct Answer: a) Exceptions thrown inside generators can be caught using `try...catch` around generator execution or iterator `.throw()` calls.
Explanation:
Generators integrate cleanly with try/catch and support injecting errors via iterator.throw().

33. What is the purpose of error boundaries in frontend UI frameworks like React?

a) To catch JavaScript errors anywhere in their child component tree, log those errors, and display fallback UI instead of crashing the whole app.
b) To prevent CSS styling conflicts between components.
c) To handle asynchronous fetch network timeouts.
d) To encrypt user input data.
Correct Answer: a) To catch JavaScript errors anywhere in their child component tree, log those errors, and display fallback UI instead of crashing the whole app.
Explanation:
Error boundaries isolate component render crashes, preserving overall application stability.

34. Can synchronous `try...catch` catch errors thrown inside event listeners attached via `addEventListener`?

a) No, because event listener callbacks execute asynchronously as macrotasks when events fire, outside the initial try/catch scope.
b) Yes, event listeners are wrapped automatically.
c) Yes, if using capture phase.
d) Only in strict mode.
Correct Answer: a) No, because event listener callbacks execute asynchronously as macrotasks when events fire, outside the initial try/catch scope.
Explanation:
Like setTimeout, event listeners run later in the event loop, requiring try/catch inside the listener callback itself.

35. What is the best practice for handling errors in Express.js middleware?

a) Passing errors to the next function (`next(err)`) so they reach centralized error-handling middleware.
b) Using synchronous try/catch blocks around route definitions.
c) Throwing uncaught exceptions directly in route handlers.
d) Ignoring errors to keep server uptime high.
Correct Answer: a) Passing errors to the next function (`next(err)`) so they reach centralized error-handling middleware.
Explanation:
Express expects error-first callback routing or `next(err)` invocation for centralized error handling.

36. What is the purpose of error codes (e.g., `err.code`) on Node.js system errors?

a) To provide programmatic string identifiers (like 'ENOENT' or 'ECONNREFUSED') indicating the exact nature of system failures.
b) To store cryptographic hashes of error logs.
c) To track the line number where the error occurred.
d) To measure execution time in milliseconds.
Correct Answer: a) To provide programmatic string identifiers (like 'ENOENT' or 'ECONNREFUSED') indicating the exact nature of system failures.
Explanation:
Error codes allow robust programmatic handling of specific system/OS failures.

37. What happens if you omit the catch binding parameter in ES2019+ (e.g., `try { ... } catch { ... }`)?

a) The error object is omitted when you don't need to inspect or reference it, making catch clauses cleaner.
b) It throws a SyntaxError.
c) It catches zero errors.
d) It throws an automatic generic error.
Correct Answer: a) The error object is omitted when you don't need to inspect or reference it, making catch clauses cleaner.
Explanation:
Optional catch binding allows writing catch blocks without declaring unused error parameters.

38. What is a null pointer exception equivalent in JavaScript?

a) A TypeError thrown when trying to read properties or call methods on `null` or `undefined` (e.g., `Cannot read properties of undefined`).
b) A ReferenceError thrown for undeclared variables.
c) A SyntaxError thrown for missing brackets.
d) A RangeError thrown for negative numbers.
Correct Answer: a) A TypeError thrown when trying to read properties or call methods on `null` or `undefined` (e.g., `Cannot read properties of undefined`).
Explanation:
Accessing properties on null/undefined is the most common TypeError in JavaScript.

39. How does optional chaining (`?.`) help prevent TypeErrors?

a) It short-circuits property access and returns `undefined` instead of throwing a TypeError if an intermediate reference is `null` or `undefined`.
b) It automatically initializes null variables to zero.
c) It converts objects into primitive strings.
d) It wraps property access in a try/catch block automatically.
Correct Answer: a) It short-circuits property access and returns `undefined` instead of throwing a TypeError if an intermediate reference is `null` or `undefined`.
Explanation:
Optional chaining safely evaluates deeply nested properties without crashing on nullish values.

40. How does the nullish coalescing operator (`??`) assist in error prevention and fallback logic?

a) It returns the right-hand fallback operand only when the left-hand operand is strictly `null` or `undefined`, avoiding falsy bugs associated with `||`.
b) It throws an error if variables are null.
c) It catches runtime exceptions.
d) It checks for syntax errors.
Correct Answer: a) It returns the right-hand fallback operand only when the left-hand operand is strictly `null` or `undefined`, avoiding falsy bugs associated with `||`.
Explanation:
Nullish coalescing safely provides defaults without falsely overriding valid falsy values like `0` or `false`.

41. What is the output of catching an error and rethrowing it (`throw err`)?

a) The original error propagates upward to outer handlers while preserving its original stack trace and error type.
b) It converts the error into a generic string.
c) It clears the error from memory.
d) It resets the stack trace to the catch block.
Correct Answer: a) The original error propagates upward to outer handlers while preserving its original stack trace and error type.
Explanation:
Rethrowing preserves the exact error object and call stack for upstream handlers.

42. What is an anti-pattern when rethrowing errors in catch blocks?

a) Throwing a new `Error` object using `throw new Error(err.message)`, which overwrites and destroys the original stack trace.
b) Using `throw err` directly.
c) Logging the error before throwing.
d) Using finally blocks for cleanup.
Correct Answer: a) Throwing a new `Error` object using `throw new Error(err.message)`, which overwrites and destroys the original stack trace.
Explanation:
Wrapping errors with `new Error()` discards the original stack trace, making root-cause debugging difficult.

43. What is error suppression (swallowing errors), and why is it dangerous?

a) Catching an error and doing nothing in the catch block, which hides bugs, causes silent failures, and makes debugging extremely difficult.
b) Logging errors to external servers.
c) Failing fast during compilation.
d) Using optional chaining.
Correct Answer: a) Catching an error and doing nothing in the catch block, which hides bugs, causes silent failures, and makes debugging extremely difficult.
Explanation:
Empty catch blocks swallow errors silently, masking critical application failures.

44. What is the purpose of assertion libraries or assertion functions (e.g., `console.assert()`)?

a) To test if conditions evaluate to true during execution, throwing or logging errors immediately if assertions fail.
b) To format JSON strings.
c) To handle asynchronous promise rejections.
d) To compile TypeScript code.
Correct Answer: a) To test if conditions evaluate to true during execution, throwing or logging errors immediately if assertions fail.
Explanation:
Assertions validate invariants and assumptions during development.

45. How do debugging source maps assist in error handling and troubleshooting minified production code?

a) They map compiled/minified production stack trace line numbers back to the original source code files and lines for developers.
b) They automatically catch and fix runtime exceptions in production.
c) They encrypt error messages for security.
d) They speed up JavaScript execution speed.
Correct Answer: a) They map compiled/minified production stack trace line numbers back to the original source code files and lines for developers.
Explanation:
Source maps bridge minified production errors back to readable original source lines.

46. What is the role of global error monitoring services (e.g., Sentry, LogRocket) in modern web applications?

a) To automatically capture uncaught exceptions, unhandled rejections, and user session context in production for real-time monitoring and alerting.
b) To write unit tests automatically.
c) To compile JavaScript into WebAssembly.
d) To replace try/catch blocks in code.
Correct Answer: a) To automatically capture uncaught exceptions, unhandled rejections, and user session context in production for real-time monitoring and alerting.
Explanation:
Production error tracking services aggregate runtime crashes and telemetry for developers.

47. Can `try...catch` catch errors thrown during synchronous JSON parsing via `JSON.parse()`?

a) Yes, `JSON.parse()` throws a SyntaxError on malformed JSON strings, which can be caught using a synchronous `try...catch` block.
b) No, JSON parsing errors can only be caught using promise `.catch()`.
c) No, JSON errors never throw exceptions.
d) Only in Node.js environments.
Correct Answer: a) Yes, `JSON.parse()` throws a SyntaxError on malformed JSON strings, which can be caught using a synchronous `try...catch` block.
Explanation:
JSON.parse is synchronous and throws catchable SyntaxErrors when given invalid JSON.

48. What happens when you pass an invalid format string to `JSON.parse()` inside a try block?

a) A SyntaxError is thrown and immediately caught by the catch block.
b) It returns null silently.
c) It ignores the error and returns an empty object.
d) It reloads the webpage.
Correct Answer: a) A SyntaxError is thrown and immediately caught by the catch block.
Explanation:
Invalid JSON strings trigger SyntaxError exceptions during parsing.

49. What is the output of `try { throw new Error('A'); } catch (e) { throw new Error('B'); } finally { console.log('C'); }` if unhandled externally?

a) It logs 'C' and then throws error 'B' (since the finally block executes before the catch error propagates).
b) It throws error 'A'.
c) It logs nothing and crashes.
d) It throws both errors simultaneously.
Correct Answer: a) It logs 'C' and then throws error 'B' (since the finally block executes before the catch error propagates).
Explanation:
The finally block always executes on exit, logging 'C', after which the error thrown in catch ('B') propagates outward.

50. Why is handling errors properly critical for enterprise software reliability?

a) It prevents catastrophic application crashes, protects sensitive internal system details from leaking to users, and ensures graceful degradation.
b) It eliminates the need for unit testing.
c) It guarantees 100% network uptime.
d) It reduces database storage requirements.
Correct Answer: a) It prevents catastrophic application crashes, protects sensitive internal system details from leaking to users, and ensures graceful degradation.
Explanation:
Robust error handling safeguards user experience, security, and application stability.

51. What is a deadlock error scenario in concurrent or asynchronous programming?

a) A situation where two or more operations are blocked indefinitely, waiting for each other to release resources or resolve.
b) An error thrown when CPU memory fills up.
c) A syntax error in async/await functions.
d) A network timeout failure.
Correct Answer: a) A situation where two or more operations are blocked indefinitely, waiting for each other to release resources or resolve.
Explanation:
Deadlocks occur in multi-resource locking or sync coordination failures.

52. How does JavaScript's single-threaded nature affect exception handling compared to multi-threaded languages?

a) Exceptions propagate up a single call stack on the main thread, avoiding complex multi-thread race condition crashes, though unhandled errors still halt execution.
b) JavaScript cannot throw exceptions because it is single-threaded.
c) Exceptions require manual thread synchronization locks.
d) Multi-threaded languages do not use try/catch.
Correct Answer: a) Exceptions propagate up a single call stack on the main thread, avoiding complex multi-thread race condition crashes, though unhandled errors still halt execution.
Explanation:
Single-threaded execution simplifies stack trace tracking and exception propagation.

53. What is the difference between a warning and an error in runtime environments?

a) A warning alerts developers to potential deprecated or risky code without halting execution, whereas an error represents a failure that disrupts normal execution flow.
b) Warnings throw catchable SyntaxErrors automatically.
c) Errors are logged only in production, while warnings are logged in development.
d) There is no functional distinction.
Correct Answer: a) A warning alerts developers to potential deprecated or risky code without halting execution, whereas an error represents a failure that disrupts normal execution flow.
Explanation:
Warnings inform without crashing, while errors represent actual execution failures.

54. What does `console.warn()` do in JavaScript?

a) Outputs a warning message to the console, typically highlighted in yellow to alert developers without interrupting program execution.
b) Throws an uncaught exception.
c) Pauses the event loop.
d) Clears all console logs.
Correct Answer: a) Outputs a warning message to the console, typically highlighted in yellow to alert developers without interrupting program execution.
Explanation:
console.warn flags non-critical warnings in developer consoles.

55. How can you implement exponential backoff retry logic for failing asynchronous operations (like network fetch requests)?

a) By wrapping the operation in a try/catch or promise catch block that recursively retries with progressively longer delays (e.g., multiplying delay by 2) upon failure.
b) By using synchronous while loops.
c) By setting `window.retryCount = 3`.
d) Exponential backoff is natively built into all JavaScript functions.
Correct Answer: a) By wrapping the operation in a try/catch or promise catch block that recursively retries with progressively longer delays (e.g., multiplying delay by 2) upon failure.
Explanation:
Exponential backoff prevents overwhelming failing servers by spacing out retry attempts.

56. What is graceful degradation in error-prone web applications?

a) Designing an application to maintain core functionality or display friendly fallback UI even when specific features or network requests fail.
b) Shutting down the server immediately upon error.
c) Disabling JavaScript entirely when errors occur.
d) Hiding error messages from developers.
Correct Answer: a) Designing an application to maintain core functionality or display friendly fallback UI even when specific features or network requests fail.
Explanation:
Graceful degradation ensures users retain basic utility despite partial system failures.

57. What is progressive enhancement?

a) Building a foundational core experience that works universally, and then layering advanced features on top for capable browsers.
b) Upgrading Node.js versions automatically.
c) Catching all errors using try/catch blocks.
d) Increasing CPU clock speeds during runtime.
Correct Answer: a) Building a foundational core experience that works universally, and then layering advanced features on top for capable browsers.
Explanation:
Progressive enhancement focuses on rock-solid core functionality before adding enhancements.

58. What is the purpose of the `cause` property in modern Error objects (ES2022)?

a) To chain underlying root-cause errors by passing `{ cause: originalError }` into `new Error()`, preserving error context across layers.
b) To specify the event loop cause of a crash.
c) To filter error logs by category.
d) To trigger automatic retries.
Correct Answer: a) To chain underlying root-cause errors by passing `{ cause: originalError }` into `new Error()`, preserving error context across layers.
Explanation:
The `cause` option allows wrapping lower-level errors into higher-level errors cleanly.

59. How do you inspect the root cause error when using the ES2022 `cause` property?

a) By accessing `error.cause` on the caught error instance.
b) Using `error.stackTrace()`.
c) By checking `error.parent`.
d) Root causes cannot be inspected.
Correct Answer: a) By accessing `error.cause` on the caught error instance.
Explanation:
error.cause exposes the original underlying error object that triggered the wrapper exception.

60. What is the output of `try { return 1; } finally { return 2; }`?

a) `2` (because the return statement in the finally block overrides the try block's return value)
b) `1`
c) `undefined`
d) `TypeError`
Correct Answer: a) `2` (because the return statement in the finally block overrides the try block's return value)
Explanation:
Finally block returns always supersede try/catch returns.

61. What is the output of `try { throw new Error('try'); } catch (e) { throw new Error('catch'); } finally { console.log('finally'); }` if unhandled?

a) It logs 'finally' and throws the error from the catch block ('catch').
b) It throws the error from the try block ('try').
c) It logs nothing.
d) It suppresses all errors.
Correct Answer: a) It logs 'finally' and throws the error from the catch block ('catch').
Explanation:
The error thrown in catch replaces the try error, and finally executes before propagation.

62. Can asynchronous generator functions use `try...catch` with `yield` and `await`?

a) Yes, `try...catch` can wrap `await` and `yield` expressions in async generators to handle thrown exceptions or injected `.throw()` errors.
b) No, async generators cannot handle errors.
c) Only in synchronous code.
d) Only when using callbacks.
Correct Answer: a) Yes, `try...catch` can wrap `await` and `yield` expressions in async generators to handle thrown exceptions or injected `.throw()` errors.
Explanation:
Async generators fully support try/catch around both asynchronous awaits and yields.

63. What is a core advantage of using custom error classes over throwing generic Error objects?

a) They allow callers to use `instanceof` checks to distinguish specific error types and handle them accordingly.
b) They execute 10x faster in V8 engines.
c) They prevent stack overflows automatically.
d) They eliminate the need for try/catch blocks.
Correct Answer: a) They allow callers to use `instanceof` checks to distinguish specific error types and handle them accordingly.
Explanation:
Custom classes enable type-safe error handling via `err instanceof DatabaseError`.

64. How do you check for a specific custom error type in a catch block?

a) Using the `instanceof` operator (e.g., `if (err instanceof CustomError) { ... }`)
b) Checking `err.name === 'Error'`
c) Comparing `err.code === 500`
d) Using `typeof err === 'CustomError'`
Correct Answer: a) Using the `instanceof` operator (e.g., `if (err instanceof CustomError) { ... }`)
Explanation:
instanceof verifies prototype inheritance matching for custom error classes.

65. What should you do in a catch block when an error is of an unknown or unexpected type?

a) Rethrow the error (`throw err`) so it doesn't get silently swallowed or mishandled by incorrect fallback logic.
b) Convert it into a string and ignore it.
c) Return null immediately.
d) Reload the browser window.
Correct Answer: a) Rethrow the error (`throw err`) so it doesn't get silently swallowed or mishandled by incorrect fallback logic.
Explanation:
Unrecognized errors should always be rethrown to avoid masking unexpected bugs.

66. What is the purpose of input sanitization and validation before processing data in JavaScript?

a) To reject malformed or malicious data early, preventing downstream exceptions, security vulnerabilities (like XSS or injection), and type errors.
b) To compress payload file sizes.
c) To speed up CSS rendering.
d) To automate garbage collection.
Correct Answer: a) To reject malformed or malicious data early, preventing downstream exceptions, security vulnerabilities (like XSS or injection), and type errors.
Explanation:
Early validation stops invalid data from triggering runtime exceptions later.

67. What is a stack overflow error, and what causes it in JavaScript?

a) An error thrown when the call stack exceeds its maximum fixed size, typically caused by infinite recursive function calls without a base case.
b) An error thrown when RAM hardware fails.
c) An error thrown when CSS grid overflows.
d) An error thrown when arrays exceed 4GB.
Correct Answer: a) An error thrown when the call stack exceeds its maximum fixed size, typically caused by infinite recursive function calls without a base case.
Explanation:
Infinite recursion exhausts call stack frames, triggering a RangeError stack overflow.

68. How does tail call optimization (TCO) relate to recursion and stack overflow errors in ECMAScript?

a) TCO allows engines to reuse stack frames when a function calls itself as its absolute final action, preventing stack overflow (though support varies across engines).
b) TCO automatically converts recursion into while loops.
c) TCO eliminates all runtime exceptions.
d) TCO speeds up network fetch requests.
Correct Answer: a) TCO allows engines to reuse stack frames when a function calls itself as its absolute final action, preventing stack overflow (though support varies across engines).
Explanation:
Tail call optimization optimizes tail-recursive calls to prevent stack exhaustion.

69. What is the difference between error handling on the client-side (browsers) vs server-side (Node.js)?

a) Client-side errors focus on UI recovery, rendering fallbacks, and user feedback, whereas server-side errors focus on process stability, request logging, and secure HTTP status responses.
b) Server-side code cannot use try/catch blocks.
c) Client-side code throws no TypeErrors.
d) There is no difference in error handling strategies.
Correct Answer: a) Client-side errors focus on UI recovery, rendering fallbacks, and user feedback, whereas server-side errors focus on process stability, request logging, and secure HTTP status responses.
Explanation:
Environments dictate distinct recovery priorities (UI resilience vs server process uptime).

70. What is the significance of HTTP status codes (e.g., 400, 401, 500) in web API error handling?

a) They provide standardized numerical indicators communicated by servers to clients regarding the success or failure category of API requests.
b) They indicate JavaScript memory consumption levels.
c) They measure browser frame rates.
d) They represent CSS stylesheet error counts.
Correct Answer: a) They provide standardized numerical indicators communicated by servers to clients regarding the success or failure category of API requests.
Explanation:
HTTP status codes categorize API responses for client-side error handling logic.

71. How should client-side code handle a fetch request returning a 500 Internal Server Error status?

a) Check `response.ok` or `response.status`, throw an error if unsuccessful, and handle it in a catch block or error state UI.
b) Assume the request succeeded because the fetch promise resolved.
c) Ignore the status code entirely.
d) Automatically restart the server.
Correct Answer: a) Check `response.ok` or `response.status`, throw an error if unsuccessful, and handle it in a catch block or error state UI.
Explanation:
Fetch only rejects on network failures; HTTP error statuses (like 500) require manual `response.ok` checks.

72. What is the purpose of a circuit breaker pattern in distributed software error handling?

a) To temporarily stop making requests to a failing downstream service after repeated failures, allowing it time to recover rather than spamming it with requests.
b) To shut down the computer when power surges occur.
c) To blow fuses in hardware motherboards.
d) To reset browser cache memory.
Correct Answer: a) To temporarily stop making requests to a failing downstream service after repeated failures, allowing it time to recover rather than spamming it with requests.
Explanation:
Circuit breakers prevent cascading failures in microservices and distributed APIs.

73. What is a graceful shutdown in Node.js server error handling?

a) Catching fatal uncaught exceptions or SIGTERM signals, closing active database/server connections cleanly, and exiting the process safely.
b) Killing the process instantly without releasing ports.
c) Reloading the script file in an infinite loop.
d) Ignoring uncaught exceptions completely.
Correct Answer: a) Catching fatal uncaught exceptions or SIGTERM signals, closing active database/server connections cleanly, and exiting the process safely.
Explanation:
Graceful shutdowns prevent data corruption and dropped connections during server crashes.

74. Why should you avoid logging sensitive user data (like passwords or tokens) in error logs?

a) To prevent security breaches, credential leakage, and compliance violations (such as GDPR or HIPAA).
b) To reduce log file storage sizes.
c) To speed up string formatting.
d) Sensitive data cannot be logged in JavaScript.
Correct Answer: a) To prevent security breaches, credential leakage, and compliance violations (such as GDPR or HIPAA).
Explanation:
Sanitizing error logs prevents accidental exposure of PII and credentials.

75. What is the primary benefit of structured error logging (JSON format) over plain text error logging?

a) Structured logs allow automated log aggregation tools (like Elasticsearch or Datadog) to parse, query, and filter error metadata efficiently.
b) JSON logs take up zero disk space.
c) Plain text logs are illegal in production.
d) Structured logs execute faster in V8.
Correct Answer: a) Structured logs allow automated log aggregation tools (like Elasticsearch or Datadog) to parse, query, and filter error metadata efficiently.
Explanation:
JSON-structured logs enable powerful querying and automated monitoring alert pipelines.

76. What is the output of `try { throw 'myError'; } catch (err) { console.log(err); }`?

a) `myError`
b) `Error: myError`
c) `ReferenceError`
d) `undefined`
Correct Answer: a) `myError`
Explanation:
Throwing a primitive string 'myError' catches the exact string value in the catch block parameter.

77. Can you catch asynchronous errors thrown inside `fs.readFile()` callback in Node.js using synchronous `try...catch`?

a) No, because `fs.readFile()` is asynchronous and passes errors to its callback function parameter instead of throwing them synchronously.
b) Yes, try/catch wraps all Node.js file system methods.
c) Yes, if using strict mode.
d) Only on Windows operating systems.
Correct Answer: a) No, because `fs.readFile()` is asynchronous and passes errors to its callback function parameter instead of throwing them synchronously.
Explanation:
Node.js error-first callbacks pass errors as arguments to callback functions rather than throwing synchronous exceptions.

78. How do you handle errors in Node.js error-first callback patterns?

a) By checking if the first parameter of the callback (`err`) is truthy before processing data.
b) Using synchronous try/catch blocks around the asynchronous function call.
c) Using `.catch()` promise methods on callbacks.
d) Callback errors are ignored automatically.
Correct Answer: a) By checking if the first parameter of the callback (`err`) is truthy before processing data.
Explanation:
Error-first callbacks convention requires checking `if (err) { handle(err); }` first.

79. What is the purpose of `util.promisify()` in Node.js regarding error handling?

a) To convert error-first callback asynchronous functions into promise-returning functions, enabling `async/await` and `.catch()` error handling.
b) To compile JavaScript into native machine code.
c) To catch uncaught global exceptions.
d) To encrypt error messages.
Correct Answer: a) To convert error-first callback asynchronous functions into promise-returning functions, enabling `async/await` and `.catch()` error handling.
Explanation:
promisify bridges legacy callback APIs with modern async/await try/catch error handling.

80. What is the output of `console.log(Error.prototype.isPrototypeOf(new TypeError()))`?

a) `true`
b) `false`
c) `undefined`
d) `TypeError`
Correct Answer: a) `true`
Explanation:
All built-in error types inherit from Error.prototype, so `Error.prototype.isPrototypeOf` returns true for TypeError instances.

81. What is the output of `new Error() instanceof SyntaxError`?

a) `false`
b) `true`
c) `undefined`
d) `TypeError`
Correct Answer: a) `false`
Explanation:
A generic base Error instance is not a SyntaxError instance.

82. Why is mastering exception and error handling crucial for professional JavaScript developers?

a) It ensures application resilience, simplifies debugging, prevents data corruption, and guarantees professional-grade software reliability under failure conditions.
b) It is only required for writing database drivers.
c) It replaces the need for CSS design.
d) It makes the V8 engine compile TypeScript.
Correct Answer: a) It ensures application resilience, simplifies debugging, prevents data corruption, and guarantees professional-grade software reliability under failure conditions.
Explanation:
Robust error management distinguishes production-grade software from fragile prototypes.
← Previous: JavaScript DOM Manipulation MCQs
Next →: JavaScript ES6 Features MCQs
NewPython Arrays MCQs

Python Arrays MCQs

Unlike many other programming languages, Python does not have a built-in static array data structure in its core syntax, instead…

By MCQs Generator
NewJavaScript DOM Manipulation MCQs

JavaScript DOM Manipulation MCQs

The Document Object Model (DOM) is a cross-platform programming interface that treats HTML and XML documents as a hierarchical tree…

By MCQs Generator
NewJavaScript Event Handling MCQs

JavaScript Event Handling MCQs

Event handling in JavaScript allows developers to build interactive web applications by listening for user interactions such as mouse clicks,…

By MCQs Generator