我如何打印错误/异常在except:块?
try:
...
except:
print(exception)
我如何打印错误/异常在except:块?
try:
...
except:
print(exception)
当前回答
我建议使用try-except语句。此外,日志异常不是使用print语句,而是在记录器上记录级别为ERROR的消息,我发现这比print输出更有效。该方法只能从异常处理程序调用,如下所示:
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
如果你想了解更多关于日志记录和调试的知识,这个python页面上有很好的文档。
其他回答
在Python 2.6或更高版本中,它更简洁:
except Exception as e: print(e)
在较旧的版本中,它仍然是相当可读的:
except Exception, e: print e
如果您想这样做的话,可以使用assert语句来引发一行错误。这将帮助您编写静态可修复的代码并及早检查错误。
assert type(A) is type(""), "requires a string"
traceback模块提供了格式化和打印异常及其回溯信息的方法,例如,这将像默认处理程序一样打印异常:
import traceback
try:
1/0
except Exception:
traceback.print_exc()
输出:
Traceback (most recent call last):
File "C:\scripts\divide_by_zero.py", line 4, in <module>
1/0
ZeroDivisionError: division by zero
#试试这个
try:
print("Hare Krishna!")
except Exception as er:
print(er)
我建议使用try-except语句。此外,日志异常不是使用print语句,而是在记录器上记录级别为ERROR的消息,我发现这比print输出更有效。该方法只能从异常处理程序调用,如下所示:
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
如果你想了解更多关于日志记录和调试的知识,这个python页面上有很好的文档。