简体   繁体   English

如何检查哪个语句引发了异常?

[英]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.

相关问题 Python:运行一条无效的语句,只是检查是否引发了异常? - Python: Run a statement that has no effect just to check if exception gets thrown? 如何检查函数中执行了哪个return语句? - How to check which return statement was executed in a function? 你能检查在 Python 中使用 doctest 抛出异常吗? - Can you check that an exception is thrown with doctest in Python? 检查是否抛出条件或异常的最佳方法 - Best way to check if condition or exception is thrown 如何检查函数返回了哪个变量? - How to check which variable a fuction has returned? 如何在单元测试中引发异常 - How to get the exception thrown in unittest 当抛出异常时,如何适当地省略UnboundLocalError:分配前引用的局部变量? - How to proper ommit UnboundLocalError: Local variable '' referenced before assignment when exception has been thrown? 如何解决 Keras layer.get_output_shape_at() 抛出的异常“该层从未被调用过,因此没有定义的输出形状”? - How to solve the exception " The layer has never been called and thus has no defined output shape" thrown by Keras layer.get_output_shape_at()? 如何检查IF语句中的数字是否已更改,然后才执行脚本? - How to check if a number inside an IF statement has changed and only then execute a script? 如何使用 if 语句检查用户是否具有权限或角色 - How to check if a user has a permission or a role using an if statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM