Ben Lerner
Ben Lerner

Reputation: 1288

Printing exceptions in Python, instead of raising them

I want to catch a Python exception and print it rather than re-raising it. For example:

def f(x):
    try:
        return 1/x
    except:
        print <exception_that_was_raised>   

This should then do:

>>> f(0)
'ZeroDivisionError'

without an exception being raised.

Is there a way to do this, other than listing each possible exception in a giant try-except-except...except clause?

Upvotes: 3

Views: 607

Answers (3)

Alexey Sidash
Alexey Sidash

Reputation: 441

try:
    0/0
except ZeroDivisionError,e:
    print e
#will print "integer division or modulo by zero"

Something like this, Pythonic duck typing lets us to convert error instances into strings on the fly=) Good luck =)

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251096

use the message attribute of exception or e.__class__.__name__ if you want the name of the Base exception class , i.e ZeroDivisionError' in your case

In [30]: def f(x):
        try:
                return 1/x
        except Exception as e:
            print e.message
   ....:         

In [31]: f(2)
Out[31]: 0

In [32]: f(0)
integer division or modulo by zero

In python 3.x the message attribute has been removed so you can simply use print(e) or e.args[0] there, and e.__class__.__name__ remains same.

Upvotes: 9

c0x6a
c0x6a

Reputation: 437

This is how I work:

try:
    0/0
except Exception as e:
    print e

Upvotes: 3

Related Questions