Home >Backend Development >Python Tutorial >How to Print Exception Messages in Python

How to Print Exception Messages in Python

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-20 22:48:29551browse

How to Print Exception Messages in Python

Printing Exceptions in Python

Python provides a powerful exception handling mechanism to manage errors and unexpected events during program execution. To print the actual exception/error raised in the except: block, it is important to capture the exception object.

Python 2.6 and Later (including Python 3.x)

In Python 2.6 and later, including Python 3.x, you can print the exception using the following syntax:

<code class="python">try:
    ...
except Exception as e:
    print(e)</code>

The Exception as e syntax assigns the exception object to the variable e. You can then use print(e) to display the exception message.

Python 2.5 and Earlier

For Python 2.5 and earlier, the exception handling syntax is slightly different. To print the exception, you need to use:

<code class="python">try:
    ...
except Exception, e:
    print str(e)</code>

Note the comma after Exception and the use of str(e) to convert the exception object to a string for printing.

Example

For instance, if you have the following code:

<code class="python">try:
    x = int(input("Enter a number: "))
    print(f"You entered: {x}")
except Exception as e:
    print(f"Error: {e}")</code>

If the user enters a non-integer value, it will raise a ValueError exception. The except block will capture the exception and print the error message using print(e). This will display the specific error encountered, such as "ValueError: invalid literal for int()" in this case.

The above is the detailed content of How to Print Exception Messages in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn