Error Handling Questions with Answers

16 practice questions on Error Handling (Node.js & Backend APIs) with answers and step-by-step solutions. Try 10 samples below, then practise all 16 free in the AptiNest app.

Sample questions

Question 1Easy

What does this print?

class NotFoundError extends Error {
  constructor(m) { super(m); this.name = 'NotFoundError'; this.status = 404; }
}
const e = new NotFoundError('no user');
console.log(e instanceof Error, e.name, e.status);
  1. false NotFoundError 404
  2. true Error 404
  3. true NotFoundError undefined
  4. true NotFoundError 404

Answer: D. true NotFoundError 404

Explanation

Extending Error keeps instanceof Error true; the constructor sets the custom name and status fields.

Step-by-step solution

  1. E instanceof Error is true because NotFoundError extends Error.
  2. e.name is 'NotFoundError' as set in the constructor.
  3. e.status is 404 as set in the constructor.
  4. console.log outputs true NotFoundError 404.

Why the other options are wrong

  • A. false is wrong here: NotFoundError extends Error, so instanceof Error gives true.
  • B. The name is set to NotFoundError in the constructor, so Error is not what e.name shows.
  • C. status is set to 404 in the constructor, so it is not undefined.

Tip: Remember that extending Error makes instanceof Error true, and custom fields are set in the constructor.

Question 2Easy

What does this print?

try { const o = null; o.x; }
catch (e) { console.log(e.constructor.name); }
  1. TypeError
  2. ReferenceError
  3. SyntaxError
  4. NullError

Answer: A. TypeError

Explanation

Accessing a property on null is a TypeError. A ReferenceError is for using a variable that was never declared.

Step-by-step solution

  1. Accessing o.x on null throws a TypeError.
  2. The catch block logs the name of the error constructor.
  3. e.constructor.name is 'TypeError' for this case.
  4. So the output is TypeError.
  5. Final answer: TypeError.

Why the other options are wrong

  • B. Reading an undeclared variable throws ReferenceError; o is declared, so that is not the error.
  • C. SyntaxError is raised when code fails to parse; o.x is valid syntax, so it is not that.
  • D. No built-in NullError exists in JavaScript; the error is a TypeError.

Tip: Remember, accessing properties on null throws a TypeError.

Question 3Easy

Which of these is a programmer error rather than an operational error?

  1. A database connection timing out
  2. Reading a property of undefined due to a bug
  3. A user sending invalid input
  4. A remote API returning 503

Answer: B. Reading a property of undefined due to a bug

Explanation

Operational errors are expected runtime conditions to handle; programmer errors are bugs to fix in the code.

Step-by-step solution

  1. A programmer error is a bug in the code, such as using a value that does not exist.
  2. Reading a property of undefined means the code assumed a value was there when it was not.
  3. That is a bug to fix in the code, so the answer is option B.

Why the other options are wrong

  • A. A timeout is an operational error: the system is under load or unreachable at runtime.
  • C. Invalid user input is an operational problem the app should expect and handle.
  • D. A 503 from a remote API is an operational error caused by the other service.

Tip: Operational errors are expected runtime conditions (timeouts, bad input, outages); programmer errors are bugs that need a code fix.

Question 4Easy

What does this print?

function f() {
  try { return 'try'; } finally { console.log('finally'); }
}
console.log(f());
  1. try finally
  2. try
  3. finally try
  4. finally

Answer: C. finally try

Explanation

The return value is computed, the finally block runs and logs, and only then does the function return "try" to the caller.

Step-by-step solution

  1. f() reaches return 'try', and the value is saved to be returned.
  2. The finally block runs before the function returns, so it logs 'finally'.
  3. Then console.log prints the returned value 'try'. The output is finally then try. The correct answer is C (finally try).

Why the other options are wrong

  • A. The finally line is printed before 'try' is logged, so the order is wrong.
  • B. Finally still runs and prints before the returned value is logged.
  • D. The returned value 'try' is still printed by the outer console.log.

Tip: Finally always runs before the function returns, even after a return inside try.

Question 5Medium

What does this print?

try { throw 'oops'; }
catch (e) { console.log(typeof e, e instanceof Error); }
  1. object true
  2. string true
  3. string false
  4. object false

Answer: C. string false

Explanation

You can throw any value. Throwing a string gives no stack trace and fails instanceof Error, which is why throwing Error objects is preferred.

Step-by-step solution

  1. The code throws the string 'oops', not an Error object.
  2. Typeof of a string value is 'string'.
  3. A string is not an instance of Error, so instanceof is false. The output is 'string false', which is option C.

Why the other options are wrong

  • A. The thrown value is a string, not an object.
  • B. The thrown value is not an Error, so instanceof Error is false.
  • D. The thrown value is a string, so the type is 'string', and instanceof is false.

Tip: Throw Error objects so that stack traces and instanceof checks work; check thrown values before reading .message.

Question 6Medium

What is the recommended use of process.on('uncaughtException')?

  1. Swallow the error and keep serving requests as if nothing had happened
  2. Retry the failed function automatically
  3. Replace all try/catch blocks in the app
  4. Log the error, clean up, then exit and let a supervisor restart

Answer: D. Log the error, clean up, then exit and let a supervisor restart

Explanation

After an uncaught exception the process may be in an inconsistent state, so the handler should exit after logging.

Step-by-step solution

  1. process.on('uncaughtException') handles errors not caught by try/catch.
  2. It should log the error to identify what went wrong.
  3. Clean up any resources to avoid leaving the app in an inconsistent state.
  4. Exit the process gracefully so a supervisor can restart it.
  5. This ensures the app doesn't continue in an unstable state.
  6. Log the error, clean up, then exit and let a supervisor restart.

Why the other options are wrong

  • A. Continuing as if nothing happened is unsafe; the process state may be corrupt.
  • B. Retrying the failed function is not the handler's job; the process state may be unknown.
  • C. try/catch is still needed locally; this handler is only a last-resort safety net.

Tip: Always log, clean up, and exit on uncaught exceptions to avoid instability.

Question 7Medium

How should a Node HTTP server react to SIGTERM during a deployment?

  1. Ignore it and keep running
  2. Exit at once, dropping open requests
  3. Restart itself inside the same process without closing any sockets
  4. Stop taking new connections, finish in-flight ones, then exit

Answer: D. Stop taking new connections, finish in-flight ones, then exit

Explanation

Graceful shutdown with server.close() lets current requests complete, avoiding errors for users during rollouts.

Step-by-step solution

  1. SIGTERM tells the server to shut down gracefully.
  2. Server should stop new connections but let existing ones finish.
  3. After in-flight requests are done, the server exits cleanly.
  4. This avoids errors and ensures a smooth deployment.
  5. Final answer: Stop taking new connections, finish in-flight ones, then exit.

Why the other options are wrong

  • A. Ignoring SIGTERM would keep the old process alive, so the deploy cannot finish cleanly.
  • B. Exiting at once drops open requests, which a graceful shutdown is meant to avoid.
  • C. Restarting inside the same process is not a shutdown; the server should close its sockets.

Tip: Use server.close() for graceful shutdown on SIGTERM.

Question 8Medium

What does this print?

try {
  try { JSON.parse('{'); }
  catch (err) { throw new Error('config invalid', { cause: err }); }
} catch (e) {
  console.log(e.message, e.cause instanceof SyntaxError);
}
  1. config invalid true
  2. config invalid false
  3. Unexpected end of JSON input
  4. config invalid undefined

Answer: A. config invalid true

Explanation

The cause option attaches the original SyntaxError to the new error, keeping the root cause while adding context.

Step-by-step solution

  1. First JSON.parse('{') throws a SyntaxError because of missing closing brace.
  2. The inner catch block throws a new Error with cause set to the original SyntaxError.
  3. The outer catch block logs e.message which is 'config invalid' and checks if e.cause is an instance of SyntaxError.
  4. e.cause instanceof SyntaxError returns true because the cause is indeed a SyntaxError.
  5. So console.log outputs 'config invalid true'.
  6. Final answer: config invalid true.

Why the other options are wrong

  • B. The cause is kept on the new error, so e.cause is a SyntaxError and the check is true.
  • C. The message is config invalid, not the JSON parser's text, since the outer error was thrown.
  • D. cause is supported as an option in the Error constructor, so it is not undefined.

Tip: Use { cause: err } to track nested errors and check e.cause for type.

Question 9Hard

Why is setting process.exitCode = 1 often safer than calling process.exit(1)?

  1. exitCode makes the process restart automatically
  2. exit() stops at once and may drop pending async writes
  3. exit(1) is not allowed inside modules
  4. exitCode sends the error to the parent shell immediately

Answer: B. exit() stops at once and may drop pending async writes

Explanation

process.exit() terminates even if stdout or file writes are still pending. Setting exitCode lets the event loop finish and then exit with that code.

Step-by-step solution

  1. Calling process.exit(1) stops the process immediately.
  2. Pending asynchronous work, such as log or file writes, may not finish and can be lost.
  3. Setting process.exitCode = 1 lets the process end normally and flush its work, so the answer is option B.

Why the other options are wrong

  • A. ExitCode only sets the exit status code; it does not restart anything.
  • C. exit(1) is an ordinary function call and is allowed in modules.
  • D. The exit code is reported when the process ends; it is not sent to the shell immediately.

Tip: Prefer process.exitCode for normal error exits so pending work can finish; reserve process.exit for emergencies.

Question 10Hard

What does this script print with default Node settings?

const p = Promise.reject(new Error('x'));
setTimeout(() => p.catch(e => console.log('handled', e.message)), 10);
  1. Nothing; the process crashes first
  2. handled x
  3. handled x, then a warning
  4. x

Answer: A. Nothing; the process crashes first

Explanation

No handler is attached by the time the microtask queue drains, so Node treats the rejection as unhandled and exits before the timer can attach .catch().

Step-by-step solution

  1. The promise is rejected at once, and no catch handler is attached in the same tick.
  2. Node checks for unhandled rejections after the current work and microtasks finish, well before the 10 ms timer.
  3. With default settings the rejection is treated as fatal, so the process exits before the timer runs. The answer is option A.

Why the other options are wrong

  • B. The timer callback never runs because the process has already crashed.
  • C. There is no warning path here; the default mode crashes instead.
  • D. The message 'x' is never printed, since the catch is never reached.

Tip: Attach the catch handler in the same synchronous tick as the promise is created; a later catch is too late under default settings.

Practise all 16 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Node.js & Backend APIs topics · All topics