user984003
user984003

Reputation: 29597

Catch all errors and display the type of error and message

I'm trying to make a generic error handler, something like "when others" in Oracle. The examples that I can find all involve catching a specific expected error.

Try:
    some_function()
Except: #I don't know what error I'm getting
    show_me_error(type_of_error_and_message)

Upvotes: 16

Views: 61698

Answers (4)

DrTyrsa
DrTyrsa

Reputation: 31991

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'>)

Upvotes: 44

NVS
NVS

Reputation: 401

import traceback

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

Upvotes: 11

Kalob Taulien
Kalob Taulien

Reputation: 1918

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

Upvotes: 4

devdrc
devdrc

Reputation: 2127

To print an exception in Python 3:

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

Upvotes: 0

Related Questions