How to get exception message in Python properly
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, the most common way to get an exception message is to catch the exception as a variable and call str() on it. That is enough for many cases, but it is not the whole story. Good error handling also needs to consider exception type, traceback, and whether the message should be shown to a user, logged for operators, or re-raised for another layer to handle.
Catch the Exception Object
The normal pattern is:
For built-in exceptions, str(exc) usually gives the human-readable message. This is the most direct answer when you just want the message text.
str, repr, and args Are Not the Same
An exception object exposes several useful views:
- '
str(exc)gives the normal readable message' - '
repr(exc)shows a more debugging-oriented representation' - '
exc.argscontains the raw argument tuple passed to the exception'
These can look different. For debugging, repr(exc) is often more informative. For user-facing error text, str(exc) is usually the better choice.
Use Logging for Real Error Reporting
If an exception should be recorded, logging the traceback is often more useful than printing only the message.
logging.exception(...) automatically includes the traceback when called inside an except block. That is usually better than manually logging only str(exc), because the stack context matters.
Get the Full Traceback When Needed
Sometimes you need the full traceback as text, for example in custom error reporting or test diagnostics. Use the traceback module.
This gives you both the short human message and the full failure context.
Be Careful with Broad Exception Handling
Getting the message properly also means catching the right exception. Code such as this is usually too broad:
It may be acceptable at an application boundary, but deep inside business logic it can hide useful distinctions. Often the better pattern is:
- catch a specific exception when you know how to handle it
- log or re-raise unexpected exceptions
That keeps error handling explicit instead of flattening everything into one generic message.
Chained Exceptions Need Attention
Python supports exception chaining with raise ... from .... In those cases, the top-level message may not tell the whole story.
If this is caught later, the visible message may be the RuntimeError text, but the original ValueError is still attached as __cause__. That matters when debugging layered code.
Do Not Depend on Message Text for Program Logic
Exception messages are for humans. They can vary by Python version, library version, and exception type. If your code needs to branch on the error, branch on the exception class, not the string message.
Bad pattern:
Better pattern:
This makes the code more stable and easier to understand.
Common Pitfalls
- Treating
str(exc)as the only useful exception detail when traceback or type also matters. - Catching overly broad exceptions and flattening unrelated failures into one message.
- Logging only the message and losing the traceback.
- Parsing exception message text to drive program logic.
- Forgetting that chained exceptions may hide the original lower-level cause unless inspected.
Summary
- The usual way to get an exception message in Python is
str(exc)insideexcept ... as exc. - '
repr(exc)andexc.argscan also be useful, especially during debugging.' - For operational visibility, prefer
logging.exception(...)ortraceback.format_exc()over bare prints. - Catch specific exception types whenever possible.
- Use exception classes for logic and messages for humans.
Related reading
- How to get exit code when using Python subprocess communicate method?
- How to get feature names selected by feature elimination in sklearn pipeline?
- How to get first element in a list of tuples?
- How to get GET request values in Django?
- How to get rid of Incremental annotation processing requested warning?
- How to get rid of tensorflow verbose messages with Keras
- How to get http headers in flask?
- How to get indices of a sorted array 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.