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.
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.
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
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()
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.
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"
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