我如何打印错误/异常在except:块?

try:
    ...
except:
    print(exception)

当前回答

#试试这个

try:

    print("Hare Krishna!")

except Exception as er:

    print(er)
    

其他回答

#试试这个

try:

    print("Hare Krishna!")

except Exception as er:

    print(er)
    

如果你想传递错误字符串,这里有一个来自错误和异常(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

在Python 2.6或更高版本中,它更简洁:

except Exception as e: print(e)

在较旧的版本中,它仍然是相当可读的:

except Exception, e: print e

我建议使用try-except语句。此外,日志异常不是使用print语句,而是在记录器上记录级别为ERROR的消息,我发现这比print输出更有效。该方法只能从异常处理程序调用,如下所示:

import logging

try:
    *code goes here*
except BaseException:
    logging.exception("*Error goes here*")

如果你想了解更多关于日志记录和调试的知识,这个python页面上有很好的文档。

对于Python 2.6及更高版本和Python 3.x:

except Exception as e: print(e)

对于Python 2.5及更早版本,使用:

except Exception,e: print str(e)