Error Handling & Debugging Interview Questions
Comprehensive error handling & debugging interview questions and answers for Python. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is the basic structure of exception handling in Python?
Basic2. How do you create and raise custom exceptions?
Basic3. What is the purpose of the 'finally' clause in exception handling?
Basic4. How do you implement logging in Python applications?
Moderate5. What is the difference between pdb and ipdb debuggers?
Moderate6. How do you handle multiple exceptions in a single except clause?
Basic7. What are context managers and how do they help in error handling?
Moderate8. How do you debug memory leaks in Python?
Advanced9. What is the difference between assertions and exceptions?
Moderate10. How do you implement error tracking in production applications?
Advanced11. What are decorators for debugging and error handling?
Advanced12. How do you handle exceptions in multithreaded applications?
Advanced13. What are the best practices for exception hierarchy design?
Moderate14. How do you debug infinite loops and recursion issues?
Moderate15. What is the role of sys.excepthook in error handling?
Advanced16. How do you implement retry logic for operations?
Moderate17. What debugging tools are available in Python IDEs?
Basic18. How do you handle exceptions in async code?
Advanced19. What are the patterns for error reporting in API development?
Moderate20. How do you debug performance issues in Python code?
Advanced21. What are the best practices for exception messages?
Basic22. How do you implement error boundaries in Python applications?
Advanced23. What are the techniques for debugging third-party library issues?
Moderate24. How do you handle database-related errors effectively?
Moderate25. What are the strategies for debugging concurrent code?
Advanced26. How do you implement error recovery mechanisms?
Advanced27. What are the patterns for handling configuration errors?
Moderate28. How do you debug memory fragmentation issues?
Advanced29. What are the best practices for logging sensitive information?
Moderate1. What is the basic structure of exception handling in Python?
BasicBasic structure uses try/except blocks: try to execute code that might raise exception, except to handle specific exceptions. Optional else clause for code when no exception occurs, finally for cleanup. Example: try: risky_operation() except TypeError: handle_error()
2. How do you create and raise custom exceptions?
BasicCreate custom exceptions by inheriting from Exception class or specific exception types. Raise using raise keyword. Include meaningful error messages and attributes. Example: class CustomError(Exception): pass; raise CustomError('message')
3. What is the purpose of the 'finally' clause in exception handling?
Basicfinally clause executes regardless of whether exception occurred or was handled. Used for cleanup operations like closing files, database connections. Executes even if return, break, or continue occurs in try/except. Ensures resource cleanup.
4. How do you implement logging in Python applications?
ModerateUse logging module with different levels (DEBUG, INFO, WARNING, ERROR, CRITICAL). Configure handlers, formatters, log destinations. Example: logging.basicConfig(level=logging.INFO). Consider log rotation, timestamp formats, context information.
5. What is the difference between pdb and ipdb debuggers?
Moderatepdb is Python's built-in debugger, ipdb adds IPython features like tab completion, syntax highlighting. Both support stepping through code, inspecting variables, setting breakpoints. Commands: n(next), s(step), c(continue), q(quit).
6. How do you handle multiple exceptions in a single except clause?
BasicGroup exceptions in tuple: except (TypeError, ValueError) as e. Access exception info using 'as' keyword. Consider exception hierarchy, order from specific to general. Handle each exception type appropriately.
7. What are context managers and how do they help in error handling?
ModerateContext managers (with statement) ensure proper resource cleanup. Implement __enter__ and __exit__ methods or use contextlib.contextmanager. Handle exceptions in __exit__. Example: file handling, database connections.
8. How do you debug memory leaks in Python?
AdvancedUse memory_profiler, tracemalloc, gc module. Monitor object references, circular references. Tools: objgraph for visualization, sys.getsizeof() for object size. Consider weak references, proper cleanup in __del__.
9. What is the difference between assertions and exceptions?
ModerateAssertions (assert condition, message) check program correctness, disabled with -O flag. Exceptions handle runtime errors. Assertions for debugging/development, exceptions for runtime error handling. Use assertions for invariants.
10. How do you implement error tracking in production applications?
AdvancedUse error tracking services (Sentry, Rollbar). Implement custom error handlers, logging middleware. Capture stack traces, context information. Consider environment-specific handling, error aggregation, alert thresholds.
11. What are decorators for debugging and error handling?
AdvancedCreate decorators for timing, logging, error catching. Example: @log_errors, @retry, @timeout. Handle function metadata using functools.wraps. Consider performance impact, logging levels.
12. How do you handle exceptions in multithreaded applications?
AdvancedUse thread-specific exception handlers, threading.excepthook. Handle exceptions within thread function. Consider thread safety in logging, global error handlers. Implement proper thread cleanup.
13. What are the best practices for exception hierarchy design?
ModerateCreate base exception class for application. Structure hierarchy based on error types. Include relevant error information, maintain backwards compatibility. Example: AppError -> ValidationError -> FieldValidationError.
14. How do you debug infinite loops and recursion issues?
ModerateUse breakpoints, print debugging, sys.setrecursionlimit(). Monitor stack traces, memory usage. Tools: pdb for stepping through code. Implement timeout mechanisms, recursion depth checking.
15. What is the role of sys.excepthook in error handling?
Advancedsys.excepthook handles uncaught exceptions. Customize for global error handling, logging. Access exception type, value, traceback. Consider different handling for different environments (dev/prod).
16. How do you implement retry logic for operations?
ModerateUse decorators or context managers for retries. Handle specific exceptions, implement backoff strategy. Example: @retry(times=3, exceptions=(NetworkError,)). Consider timeout, max attempts, delay between retries.
17. What debugging tools are available in Python IDEs?
BasicIDEs provide integrated debuggers, breakpoints, variable inspection, call stack viewing. Popular: PyCharm debugger, VS Code debugger. Features: conditional breakpoints, expression evaluation, watch variables.
18. How do you handle exceptions in async code?
AdvancedUse try/except in async functions, handle event loop exceptions. asyncio.excepthook for loop exceptions. Consider concurrent error handling, task cancellation. Example: async with AsyncExitStack().
19. What are the patterns for error reporting in API development?
ModerateImplement consistent error response format, HTTP status codes. Include error codes, messages, debug information. Consider API versioning, client error handling. Example: {error: {code: 'VAL_001', message: 'Invalid input'}}.
20. How do you debug performance issues in Python code?
AdvancedUse profilers (cProfile, line_profiler), timing decorators. Monitor CPU usage, memory allocation. Tools: py-spy for sampling profiler. Consider bottlenecks, optimization opportunities.
21. What are the best practices for exception messages?
BasicInclude specific error details, context information. Make messages user-friendly, actionable. Consider internationalization, security implications. Example: 'Failed to connect to database at host:port: timeout after 30s'.
22. How do you implement error boundaries in Python applications?
AdvancedCreate wrapper classes/functions for error containment. Handle subsystem failures gracefully. Consider component isolation, fallback behavior. Example: class ErrorBoundary context manager.
23. What are the techniques for debugging third-party library issues?
ModerateUse source-level debugging, monkey patching. Inspect library source, logging integration. Consider version compatibility, issue tracking. Tools: debugger step-into, logging interception.
24. How do you handle database-related errors effectively?
ModerateImplement specific exception handling for DB errors. Handle connection issues, transaction rollback. Consider retry logic, connection pooling. Example: handle SQLAlchemy exceptions specifically.
25. What are the strategies for debugging concurrent code?
AdvancedUse thread/process-specific logging, race condition detection. Tools: threading.VERBOSE, multiprocessing debug logs. Consider deadlock detection, thread sanitizers.
26. How do you implement error recovery mechanisms?
AdvancedCreate recovery procedures for critical errors. Implement state restoration, data consistency checks. Consider transaction boundaries, cleanup operations. Example: backup/restore mechanisms.
27. What are the patterns for handling configuration errors?
ModerateValidate configuration early, provide clear error messages. Handle missing/invalid settings gracefully. Consider environment-specific defaults, configuration versioning. Example: config validation decorators.
28. How do you debug memory fragmentation issues?
AdvancedUse memory_profiler, guppy3 for heap analysis. Monitor object lifecycle, memory patterns. Consider garbage collection timing, object pooling. Tools: objgraph for reference visualization.
29. What are the best practices for logging sensitive information?
ModerateImplement data masking, logging filters. Handle PII, credentials securely. Consider compliance requirements, log retention policies. Example: custom log formatters for sensitive data.