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.
JavaScript Error Handling MCQs for Developer Interviews & Certification
1 min read
Correct Answer: a) try...catch...finally
Explanation:
JavaScript uses the standard try...catch...finally block structure to gracefully catch and handle runtime exceptions.
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.
Correct Answer: a) Error
Explanation:
The global Error constructor creates error objects that contain a message and stack trace when thrown.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Correct Answer: a) unhandledrejection
Explanation:
The `unhandledrejection` event fires on the window when a promise rejection goes unhandled.
Correct Answer: a) error
Explanation:
The global `error` event on window catches uncaught runtime exceptions.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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`.
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.
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.
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.
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.
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.
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.
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.
Correct Answer: a) A SyntaxError is thrown and immediately caught by the catch block.
Explanation:
Invalid JSON strings trigger SyntaxError exceptions during parsing.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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`.
Correct Answer: a) Using the `instanceof` operator (e.g., `if (err instanceof CustomError) { ... }`)
Explanation:
instanceof verifies prototype inheritance matching for custom error classes.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
Correct Answer: a) `myError`
Explanation:
Throwing a primitive string 'myError' catches the exact string value in the catch block parameter.
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.
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.
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.
Correct Answer: a) `true`
Explanation:
All built-in error types inherit from Error.prototype, so `Error.prototype.isPrototypeOf` returns true for TypeError instances.
Correct Answer: a) `false`
Explanation:
A generic base Error instance is not a SyntaxError instance.
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.
Related Posts
New
New
New

Python Arrays MCQs
Unlike many other programming languages, Python does not have a built-in static array data structure in its core syntax, instead…
August 27, 2026By MCQs Generator

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…
August 29, 2026By MCQs Generator

JavaScript Event Handling MCQs
Event handling in JavaScript allows developers to build interactive web applications by listening for user interactions such as mouse clicks,…
August 29, 2026By MCQs Generator
Related Categories
New












AI & Data Science MCQ
5 topics
By MCQs Generator
New
Arts & Humanities MCQ
4 topics
By MCQs Generator
New
Civil Engineering MCQ
4 topics
By MCQs Generator
New
Commerce & Business MCQ
4 topics
By MCQs Generator
New
Competitive Exams MCQ
5 topics
By MCQs Generator
New
Electrical & Electronics Engineering MCQ
3 topics
By MCQs Generator
New
General Knowledge MCQ
2 topics
By MCQs Generator
New
General Science MCQ
4 topics
By MCQs Generator
New
Law & Judiciary MCQ
3 topics
By MCQs Generator
New
Mechanical Engineering MCQ
4 topics
By MCQs Generator
New
Medical & Health Sciences MCQ
4 topics
By MCQs Generator
New
Modern Tech Fields MCQ
3 topics
By MCQs Generator