如何在 except:
块中打印错误/异常?
try:
...
except:
print(exception)
对于 Python 2.6 及更高版本以及 Python 3.x:
except Exception as e: print(e)
对于 Python 2.5 及更早版本,请使用:
except Exception,e: print str(e)
traceback
模块为 formatting and printing exceptions 及其回溯提供方法,例如,这将像默认处理程序一样打印异常:
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
error_message = traceback.format_exc()
except Exception as ex:
...
sys.exc_info()
函数获得,而 traceback.print_exc()
函数从那里获取它。只有在不处理异常或想要显示基于不同异常的信息时,您才需要显式传递异常。
在 Python 2.6 或更高版本中,它更简洁:
except Exception as e: print(e)
在旧版本中,它仍然非常易读:
except Exception, e: print e
Python 3:日志记录
可以使用更灵活的 logging
模块来记录异常,而不是使用基本的 print()
函数。 logging
模块提供了许多额外的功能,例如将消息记录到给定的日志文件中、使用时间戳记录消息以及有关记录发生位置的附加信息。 (有关更多信息,请查看官方 documentation。)
可以使用模块级函数 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.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)
如果您想传递错误字符串,这里是来自 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
(我打算将此作为对@jldupont 答案的评论,但我没有足够的声誉。)
我在其他地方也看到过类似@jldupont 的回答。 FWIW,我认为重要的是要注意这一点:
except Exception as e:
print(e)
默认情况下会将错误输出打印到 sys.stdout
。一般来说,更合适的错误处理方法是:
except Exception as e:
print(e, file=sys.stderr)
(请注意,您必须 import sys
才能使其工作。)这样,错误将打印到 STDERR
而不是 STDOUT
,从而允许正确的输出解析/重定向/等。我知道这个问题严格来说是关于“打印错误”,但在这里指出最佳实践似乎很重要,而不是忽略这个可能导致最终不会更好地学习的人的非标准代码的细节。
我没有像 Cat Plus Plus 的回答那样使用 traceback
模块,也许这是最好的方法,但我想我会把它扔在那里。
在捕获异常时,人们几乎可以控制要显示/记录来自回溯的哪些信息。
编码
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'
print
打印 Exception
和 Exception Message
一次?每当我尝试这样做时,结果都很奇怪。
print(f"Exception: {type(exception).__name__}\nException message: {exception}")
。开头的 f
表示它是一个 f-string
,它只允许您将表达式放在花括号中,而不是使用 .format()
。 f-strings
仅适用于运行 Python 3.6+ 的系统
在这里扩展“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
#尝试这个
try:
print("Hare Krishna!")
except Exception as er:
print(er)
如果您想要这样做,可以使用 assert 语句完成一个线性错误提升。这将帮助您编写静态可修复的代码并及早检查错误。
assert type(A) is type(""), "requires a string"
assert
语句不应用于正常逻辑;如果 python 使用 -O
运行,它们将被忽略。见蟒蛇(1)。
我建议使用 try-except 语句。此外,记录异常不是使用打印语句,而是在记录器上记录级别为 ERROR 的消息,我发现这比打印输出更有效。该方法只能从异常处理程序中调用,如下所示:
import logging
try:
*code goes here*
except BaseException:
logging.exception("*Error goes here*")
如果您想了解有关日志记录和调试的更多信息,this python page 上有很好的文档。
使用 as
语句
try:
# Code
except Exception as e:
print(e)
不定期副业成功案例分享
str( KeyError('bad'))
=>'bad'
-- 不告诉异常类型print(repr(e))
;基本Exception.__str__
实现只返回异常消息,而不是类型。或者,使用traceback
模块,该模块具有打印当前异常、格式化或完整回溯的方法。print(repr(e))
不提供任何跟踪。回溯模块 (在另一个答案中提到) 中的print_exc
虽然在这种情况下有效。repr(e)
会给出堆栈跟踪?我说的是str(e)
和repr(e)
之间的区别,后者包含更多信息,您也会在回溯的最后一行看到这些信息。我在评论中明确提到了traceback
模块。