How to capture and print Python exception message?


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.

Example

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.

Example

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

Updated on: 12-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements