Error Handling and Defensive Programming Questions
Making code robust against bad input and failure: exceptions versus error returns, input validation, guard clauses, graceful degradation, and designing for the unhappy path. Covers where to handle versus propagate errors and how to fail safely without hiding bugs. A recurring probe of production maturity.
Write a helper function format_error_log(exc, context) that returns a structured log record (a dict) suitable for ingestion into a logging pipeline: timestamp, level, service, correlation_id, error_type, message, and a short stack trace, using only the standard library. Describe how you would limit sensitive data and ensure the record stays machine-parsable.
Implement a thread-safe token-bucket rate limiter (tryAcquire()/refill()) supporting configurable burst capacity and a sustained replenishment rate. Then describe how you'd apply per-tenant rate limiting, backpressure, and resource isolation (CPU/GPU/QoS) in a multi-tenant online-inference service so one noisy tenant can't degrade others, including the error-handling policy for a rejected request (429 versus queueing versus a degraded response).
Tail latency has increased because of downstream timeouts. Explain how you would implement timeouts and deadlines at multiple layers to protect the system: client SDK timeouts, HTTP client timeouts, worker thread-pool task deadlines, and a request-level deadline propagated via context or headers across service calls. Include pseudocode showing how you would enforce a global deadline and cancel subtasks when it expires, and walk through an example timeline for a request touching three services.
In modern C++, implement a small RAII wrapper FileHandle that opens a file descriptor in its constructor and guarantees close() is called in the destructor. Requirements: support move semantics (move constructor and move assignment) but disable copying; ensure the destructor is safe to run while another stack is already unwinding from an exception; discuss noexcept, resource-release guarantees, and why this pattern prevents leaks compared to manual open/close calls.
Sketch a static-analysis rule (algorithmically, or as pseudocode) that detects broad exception-swallowing patterns in Python: bare except:, except Exception: pass, or except Exception as e: return None without logging. Explain what false positives it would need to guard against, and how you would integrate it into CI.
Unlock Full Question Bank
Get access to all Error Handling and Defensive Programming interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.