Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to capture and print Python exception message?

I have code that can raise an exception

        a = 'sequel'
        b = 0.8
        print a + b

How do I catch the exception message?


1 Answer
Rajendra Dharmkar

Python exception messages can be captured and printed in different ways as shown in two code examples below. In the first one, we use the message attribute of the exception object.

try:
a = 7/0
print float(a)
except BaseException as e:
print e.message

OUTPUT

integer division or modulo by zero

In case of given code, we import the sys module and use the sys.exc_value attribute to capture and print the exception message.

import sys
def catchEverything():
try:
a = 'sequel'
b = 0.8
print a + b
except Exception as e:
print sys.exc_value
catchEverything()

OUTPUT

cannot concatenate 'str' and 'float' objects
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.