tags:

views:

312

answers:

7

Hi, is this possible:

try:
    something here
except:
    print 'the whatever error occurred.'

Is it possible to do this in 1 line? Edit...I want to print the 1 line AFTER "except:"

I simply just want to print the error, whatever that is.

A: 

Did you mean Try/Catch in Python a similar question in SO?

Shoban
+3  A: 

In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
Nick D
Very complete, although 'as' doesn't work before python 2.6
foosion
+5  A: 
except Exception,e: print str(e)
jldupont
Seems the closest to what the OP wanted.
vgm64
the `str()` part is redundant -- `print e` is exactly the same thing as `print str(e)` [[i.e., `print` does its own stringification]].
Alex Martelli
@alex: doesn't it depends on the subclass (if any) of the exception thrown? The __repr__ method might not have been implemented whilst the __str__ might have. In any case, there isn't a good substitute for an incomplete implementation I guess ;-)
jldupont
+1  A: 

traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

except: traceback.print_exc()
PiotrLegnica
+1  A: 

Why do you want to do this in one line? One of the great aspects of python is its readability. The code posted in your question is extremely readable and clear. A one-line exception handling block is much less readable, and from a practical standpoint offers no advantages to the two-line version.

Cory
A: 

One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.


assert type(A) is type(""), "requires a string"

whatnick
A: 

In Python 3 it's a bit cleaner:

except Exception as e: print(e)

In Python 2 it's still quite readable:

except Exception, e: print e
ilya n.