Getting the exception value in Python
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Exception handling in Python is most useful when you capture both the exception type and the detailed error message. The error message often explains what input failed, which key was missing, or which conversion was invalid. By extracting exception values correctly, you can log actionable diagnostics without crashing the entire application flow.
Core Sections
Capturing exception objects with as
Python binds the thrown exception instance to a variable using except SomeError as exc. This object includes message text and type specific fields. You can print it, log it, or branch on the error class.
This pattern preserves stack context because the original exception is re raised. If you replace it with a new exception without chaining, important debugging information can disappear.
Accessing traceback details for deeper debugging
For production systems, message text alone is rarely enough. The traceback module helps capture full call stacks. Combined with structured logging, this lets you inspect failures after deployment.
For web services, store this information in logs rather than returning raw traces to clients. Detailed traces can expose implementation details and create security risk.
Chaining exceptions to keep root cause
Sometimes you want a domain specific error while still keeping the original failure. Use raise NewError(...) from exc so the root cause remains visible.
This approach is cleaner than swallowing the original exception and writing a generic message. Good exception chains reduce time to diagnose incidents because developers can see both business context and low level cause.
Handling multiple exception types clearly
When one block can raise different errors, avoid catching Exception unless you truly need a top level safety net. Catching broad exceptions too early can hide programming mistakes and produce vague logs. Prefer specific handlers with targeted recovery behavior.
A useful pattern is to map technical exceptions to user facing messages near the application boundary. Keep internal exception values intact in logs, and translate only the response text that leaves your service.
Common Pitfalls
- Catching
Exceptioneverywhere and hiding real bugs. Catch specific exception types at the layer that can handle them. - Logging only custom messages without the exception object. Include the original exception value so logs remain diagnostic.
- Re raising a new exception without
from exc, which loses root cause context. Chain exceptions intentionally. - Returning raw traceback details to end users. Keep detailed traces in logs and return safe messages externally.
- Treating exception handling as control flow for normal logic. Use explicit condition checks for expected cases.
Summary
- Use
except ... as excto capture the exception value and inspect details. - Keep stack context by re raising properly and using exception chaining.
- Combine exception values with structured logging for fast debugging.
- Catch narrow exception types and implement targeted recovery.
- Preserve security by separating internal diagnostics from external error messages.
Related reading
- getting the index of a row in a pandas apply function
- Getting the index of the returned max or min item using max/min on a list
- Getting the name of a variable as a string
- Getting the SQL from a Django QuerySet
- Getting the name of the currently executing method
- Getting the PublicKeyToken of .Net assemblies
- Getting today's date in YYYY-MM-DD in Python?
- Getting today's date in YYYY-MM-DD in Python?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.