How to Print Exception Messages in Python

Mary-Kate Olsen
Release: 2024-10-20 22:48:29
Original
424 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!