[英]How to check which statement has thrown exception?
I have a statement like this. 我有这样的声明。
I just want to know which of the two assert statement has thrown the exception. 我只想知道两个assert语句中的哪一个引发了异常。
try:
assert re.search("xyz", statement)
assert re.search("abc", statement)
except AssertionError:
print "AssertionError : Expected Error message not found"
Thanks for the answer. 感谢您的回答。
As mentioned in The assert statement docs, you can give an expression after the assertion test expression; 如断言文档中所述,您可以在断言测试表达式之后给出一个表达式。 that second expression will be passed in the AssertionError.
第二个表达式将在AssertionError中传递。 Here's a simple demo:
这是一个简单的演示:
for n in (-5, 10, 20):
try:
assert 0 <= n, '%d is too low' % n
assert n <= 10, '%d is too high' % n
print('%d is ok' % n)
except AssertionError as err:
print "AssertionError:", err
output 输出
AssertionError: -5 is too low
10 is ok
AssertionError: 20 is too high
That second expression doesn't have to be a string, it can be anything. 第二个表达式不必是字符串,可以是任何东西。 Since assertions should only be used to verify program logic, not to validate user data, I generally don't bother passing a nicely-formatted string, I just pass a tuple containing the relevant values, and maybe an identifying string.
由于断言仅应用于验证程序逻辑,而不能用于验证用户数据,因此我通常不麻烦传递格式正确的字符串,而只传递包含相关值的元组,也可能传递标识字符串。 Eg,
例如,
assert (a * b > c), ('Bad product', a, b, c)
You could use functions from the traceback
module. 您可以使用
traceback
模块中的功能。 For example, extract_tb
returns a list of tuples (named tuples in Python 3.5 and newer) representing the stack trace entries. 例如,
extract_tb
返回表示堆栈跟踪条目的元组列表(在Python 3.5及更高版本中命名为元组)。 Each tuple contains a line number as well as the source text line (if available). 每个元组都包含一个行号以及源文本行(如果有)。
import traceback
try:
assert 1
assert None
except AssertionError as e:
for x in traceback.extract_tb(e.__traceback__, limit=-1):
print(x.lineno, repr(x.line)) # Prints 5 'assert None'
You are able to print the last raised exception with traceback.print_exc()
. 您可以使用
traceback.print_exc()
打印最后一个引发的异常。 An example: 一个例子:
>>> import traceback
>>> try:
... a = 1 / 0
... except:
... traceback.print_exc()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
There is also traceback.format_exc()
in case you don't want to print. 如果您不想打印,还可以使用
traceback.format_exc()
。
Maybe you want to differ the exceptions?Then Getting exception details in Python can help you. 也许您想区分异常?然后在Python中获取异常详细信息可以为您提供帮助。 Copying the answer here:
在此处复制答案:
import sys
try:
assert re.search("xyz", statement)
assert re.search("abc", statement)
except AssertionError:
type, value, traceback = sys.exc_info()
Then you can print out the info. 然后,您可以打印出信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.