use str

try:
    some_method()
except Exception as e:
    s = str(e)

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?

Answer from aaronasterling on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
>>> 10 * (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> 10 * (1/0) ~^~ ZeroDivisionError: division by zero >>> 4 + spam*3 Traceback (most recent call last): File "<stdin>", line 1, in <module> 4 + spam*3 ^^^^ NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> '2' + 2 ~~~~^~~ TypeError: can only concatenate str (not "int") to str · The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred.
Discussions

Question: How to convert Python Exception (PyErr) into string for logging
I have a python script which raises exception. How do I print this in the rust log? More on github.com
🌐 github.com
3
July 11, 2020
Exception handling in Python - Am I doing this wrong (and why?) - Software Engineering Stack Exchange
I've read many questions and articles on exception handling in Python (and in general), but I still think that it's the most confusing thing ever. I ended up doing something like this: # error cla... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
September 27, 2015
How to use Try and Except to detect if user has entered stringb or integer?
It's worth checking the official docs for a proper explanation, but for this particular case, your syntax would look something like this: try: # code that might cause a ValueError. except ValueError: # code that will happen only if a ValueError occurred above. # code that will happen regardless of whether a ValueError occurred (i.e., your program won't crash). You can leverage this concept to selectively run code if an attempt is made to convert a non-numeric string to an integer. More on reddit.com
🌐 r/learnpython
7
0
March 22, 2023
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enote.add_note("additional info") try: raise enote except Exception as exc: ... More on discuss.python.org
🌐 discuss.python.org
0
September 4, 2024
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - In the except clause, you assign the RuntimeError to the temporary variable error—often also called err—so that you can access the exception object in the indented block. In this case, you’re printing the object’s string representation, ...
🌐
Coursera
coursera.org › tutorials › how to catch, raise, and print a python exception
How to Catch, Raise, and Print a Python Exception | Coursera
August 13, 2024 - 1 2 3 4 5 6 7 try: greeting = word1+word2 print(greeting) except TypeError: print("You can only concatenate strings to strings") except: print("Something else went wrong") ... Python attempts to execute the statements within the try clause first. If an error occurs, it skips the rest of the clause and prompts the program to follow your except clause instructions.
🌐
Astral
docs.astral.sh › ruff › rules › f-string-in-exception
f-string-in-exception (EM102) | Ruff
Checks for the use of f-strings in exception constructors. Python includes the raise in the default traceback (and formatters like Rich and IPython do too).
🌐
GitHub
github.com › PyO3 › pyo3 › issues › 1034
Question: How to convert Python Exception (PyErr) into string for logging · Issue #1034 · PyO3/pyo3
July 11, 2020 - You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. ... There was an error while loading. Please reload this page. ... I have a python script which raises exception.
Author: PyO3
Find elsewhere
🌐
Linux Hint
linuxhint.com › convert-an-exception-to-a-string-in-python
How Do I Convert an Exception to a String in Python – Linux Hint
The simplest way to convert an exception to a string is via the built-in “str()” function. This function accepts an object as an argument and retrieves a string representation of the object. It returns an error message when the exception object is passed as an argument.
🌐
Python
docs.python.org › 3 › builtins › exceptions.html
Built-in Exceptions — Python 3.14.7 documentation
It is not meant to be directly ... Exception). If str() is called on an instance of this class, the representation of the argument(s) to the instance are returned, or the empty string when there were no arguments....
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-print-exception-stack-trace-in-python
How to Print Exception Stack Trace in Python - GeeksforGeeks
July 15, 2025 - Explanation: The except block catches the exception and uses traceback.format_exc() to capture the complete error traceback as a string.
🌐
Quora
theprogrammerscafe.quora.com › How-to-convert-an-exception-to-a-string-in-Python
http://www.quora.com/How-do-I-convert-an-exception-to-a-string-in-Python/answer/Tony-Flury
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
Top answer
1 of 2
10

User input sucks. You can't trust those users to get anything right, and so you've got to handle all kinds of special cases that make your life difficult. Having said that, we can minimize the difficulty with general principles.

Validate early, not often

Check input for validity as soon as it read into your program. If you read in a string that should be a number, convert it into a number right away and complain to the user if it isn't a number. Any rogue data you don't verify at input will make its way into the rest of the program and produce bugs.

Now, you can't always do this. There will be cases where you can't verify the correct properties right away, and you'll have to verify them during later processing. But you want as much verification to happen as early as possible so that you have your special cases around input logic centralized to one location as much as possible.

Use Schemas

Let's consider a function that parses some json.

def parse_student(text):
    try: 
        data = json.parse(text)
    except ValueError as error:
        raise ParseError(error)

    if not isinstance(data, dict):
        raise ParseError("Expected an object!")
    
    try:
        name = data['name']
    except KeyError:
        raise ParseError('Expected a name')

    if not isinstance(name, dict):
       raise ParseError("Expected an object for name")

    try:
        first = name['first']
    except KeyError:
        raise ParseError("Expected a first name")
    
    if not isinstance(first, basestring):
        raise ParseError("Expected first name to be a string")
    
    if first == '':
        raise ParseError("Expected non-empty first name")

That was a lot of work just to extract the first name, let alone any other attributes. We can make this a lot better if we can use a json-schema. See: http://json-schema.org/.

I can describe what my student object looks like:

{
    "type": "object",
    "properties": {
        "name": {
            "type": "object",
            "properties": {
                  "first" : {
                       "type" : "string"
                  }
            },
            "required": "first"
        },
    } 
    "required": ["name"]
}

When I parse I then do something like:

def parse_student(text):
    try: 
        data = json.parse(text)
    except ValueError as error:
        raise ParseError(error)

    try:
        validate(data, STUDENT_SCHEMA)
    except ValidationError as error:
        raise ParseError(error)

    first = data['name']['first']

Checking against the schema verifies most of the structure that I need. If the user input does not match the schema, the schema validator will produce a nice error message explaining exactly what was wrong. It will do so far more consistently and correctly then if I wrote the checking code by hand. Once the validation has been passed, I can just grab data out of the json object, because I know that it will have the correct structure.

Now, you probably aren't parsing JSON. But you may find that you can do something similar for your format that lets you reuse the basic validation logic across the different pieces of information that you fetch.

2 of 2
2

You can probably simplify your code by centralising the try/except validation of function args, and the conversion of exceptions to your exception class, into one or two decorators, which you apply to each of your methods and functions. google for python decorators for exceptions, and python decorators to validate args and you'll find stackoverflow examples like this and this.

You often don't need to explicitly validate method arguments as your code is going to cause exceptions naturally, and this might be good enough, as you cannot test for all eventualities.

Remember when writing a script, that often that your code will be even more useful if someone can include it as a library module, so make the main be specific to what a user would like from the command line, but in the library part don't try too hard to obscure where an exception stems from and so on.

🌐
W3Schools
w3schools.com › Python › python_ref_exceptions.asp
Python Built-in Exceptions
Python Overview Python Built-in ... Python Exceptions Python Glossary · Built-in Modules Random Module Requests Module Statistics Module Math Module cMath Module · Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Training ... If you want to use W3Schools ...
🌐
Python
python.org › doc › essays › stdexceptions
Standard Exception Classes in Python 1.5 | Python.org
More serious is breaking error handling code. This usually happens because the error handling code expects the exception or the value associated with the exception to have a particular type (usually string or tuple). With the new scheme, the type is a class and the value is a class instance.
🌐
Python.org
discuss.python.org › ideas
Print exception notes - in repr(exc) or otherwise - Ideas - Discussions on Python.org
September 4, 2024 - Exception notes are printed in tracebacks, but they are omitted when an exception is handled and logged or printed. I think a possibly helpful information is lost. # Python 3.11+ enote = ValueError("error message") enote.add_note("additional info") try: raise enote except Exception as exc: print(repr(exc)) # will NOT print 'additional info' Unless I overlooked something, the PEP 678 does not discuss the string representation, just the tracebacks.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-exception-handling
Python Exception Handling - GeeksforGeeks
We raise an exception using the raise keyword followed by an instance of the exception class that we want to trigger. We can choose from built-in exceptions or define our own custom exceptions by inheriting from Python's built-in ...
Published: May 29, 2026
🌐
freeCodeCamp
freecodecamp.org › news › python-print-exception-how-to-try-except-print-an-error
Python Print Exception – How to Try-Except-Print an Error
March 15, 2023 - Every programming language has its way of handling exceptions and errors, and Python is no exception. Python comes with a built-in try…except syntax with which you can handle errors and stop them from interrupting the running of your program. In thi...
🌐
Rollbar
rollbar.com › home › throwing exceptions in python
How to Throw Exceptions in Python | Rollbar
print(a % b) TypeError: not all arguments converted during string formatting Process finished with exit code 1 · Python throws the TypeError exception when there are wrong data types. Similar to TypeError, there are several built-in exceptions like:
Published: May 22, 2026
🌐
Tagline Infotech
taglineinfotech.com › home › how do i print an exception in python?
How do I Print an Exception in Python? - Tagline Infotech
December 31, 2025 - Print an Exception in Python is one of the most vital tools for debugging and expertise the behavior of your code. When an error occurs during the execution of a Python program, using try and except blocks to handle the error and printing the exception message is crucial for diagnosing what went wrong.
🌐
Bacancy Technology
bacancytechnology.com › qanda › python › python-try-except-print-error
How to print as exception in Python
July 31, 2023 - This exception object contains ... message associated with the exception. To print an exception in Python, you can use the print() function....