[Fixed]-Catch all errors and display the type of error and message

43👍

This is very well-documented. But may be you just need Sentry?

try:
    1/0
except Exception as e:
    print('%s' % type(e))

>>> 
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)

11👍

import traceback

try:
    some_function()
except Exception as e:
    message = traceback.format_exc()
    print(message)
👤NVS

4👍

To print the exception using Python 3, you’ll want to use type(e). Example below:

try:
    1/0
except Exception as e:
    print(type(e))

>>> <class 'ZeroDivisionError'>

And then you can catch the exception with:

try:
    1/0
except ZeroDivisionError:
    print('Cannot divide by 0')
except Exception as e:
    print(type(e))

>>> Cannot divide by 0

0👍

To print an exception in Python 3:

try:
    # your code
except Exception as e:
    print(e)
👤devdrc

Leave a comment