3

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?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Or if you just want the exception's name: print e.__class__.__name__
@mgilson's comment is really what the OP asked for; print repr(e) would also work.
Good, but this won't work if you raise an instance of class Whoa: pass
@alex_jordan -- If you raise things which aren't Exceptions, you deserve what you get I think ... quickly looking over the documentation, I'm not even positive that behaviour is well defined.
@BurhanKhalid I think repr(e) returns kind of combination of e.__class__.__name__ and e.args, i.e output is ZeroDivisionError('integer division or modulo by zero',)
3

This is how I work:

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

Comments

2
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 =)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.