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

try:
    ...
except:
    print(exception)

当前回答

在这里展开“except Exception as e:”的解决方案是一个很好的一行,其中包括一些额外的信息,如错误的类型和发生的位置。


try:
    1/0
except Exception as e:
    print(f"{type(e).__name__} at line {e.__traceback__.tb_lineno} of {__file__}: {e}")

输出:

ZeroDivisionError at line 48 of /Users/.../script.py: division by zero

其他回答

Python 3:日志记录

可以使用更灵活的日志模块来记录异常,而不是使用基本的print()函数。日志模块提供了很多额外的功能,例如,日志消息…

到一个给定的日志文件,或者 带有时间戳和关于日志记录发生位置的附加信息。

欲了解更多信息,请查看官方文档。


使用

可以使用模块级函数Logging .exception()来记录异常,如下所示:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

输出

ERROR:root:An exception was thrown!
Traceback (most recent call last):
File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

笔记

函数logging.exception()只能从异常处理程序调用 日志模块不应该在日志处理程序中使用,以避免RecursionError(感谢@PrakharPandey)


选择日志级别

也可以使用另一个日志级别记录异常,但仍然可以通过使用关键字参数exc_info=True显示异常细节,如下所示:

logging.critical("An exception was thrown!", exc_info=True)
logging.error   ("An exception was thrown!", exc_info=True)
logging.warning ("An exception was thrown!", exc_info=True)
logging.info    ("An exception was thrown!", exc_info=True)
logging.debug   ("An exception was thrown!", exc_info=True)

# or the general form
logging.log(level, "An exception was thrown!", exc_info=True)

仅限名称和描述

当然,如果你不想要整个回溯,而只想要一些特定的信息(例如,异常名称和描述),你仍然可以像这样使用日志模块:

try:
    1/0
except BaseException as exception:
    logging.warning(f"Exception Name: {type(exception).__name__}")
    logging.warning(f"Exception Desc: {exception}")

输出

WARNING:root:Exception Name: ZeroDivisionError
WARNING:root:Exception Desc: division by zero

如果您想这样做的话,可以使用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

在捕获异常时,可以控制显示/记录跟踪中的哪些信息。

的代码

with open("not_existing_file.txt", 'r') as text:
    pass

将产生以下回溯:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

打印/记录完整的回溯

正如其他人已经提到的,你可以通过使用traceback模块来捕获整个跟踪:

import traceback
try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    traceback.print_exc()

这将产生以下输出:

Traceback (most recent call last):
  File "exception_checks.py", line 19, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

你可以通过使用日志来达到同样的效果:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    logger.error(exception, exc_info=True)

输出:

__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
  File "exception_checks.py", line 27, in <module>
    with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'

仅打印/记录错误名称/消息

你可能对整个回溯不感兴趣,而只对最重要的信息感兴趣,比如异常名称和异常消息,使用:

try:
    with open("not_existing_file.txt", 'r') as text:
        pass
except Exception as exception:
    print("Exception: {}".format(type(exception).__name__))
    print("Exception message: {}".format(exception))

输出:

Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'

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

import logging

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

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