简体   繁体   English

Python触发函数引发异常而不修改它

[英]Python trigger function to raise exception without modifying it

With the code block: 使用代码块:

1  import re
2  import sys
3  import traceback
4 
5  def foo(arg):
6      if isinstance(arg, dict):
7         return arg.get('key', 0)
8      return 0
9  
10 arg = {}
11
12
13
14 try:
15     foo(arg)
16 except Exception:
17     lines = traceback.format_exception(*sys.exc_info())
18     for line in lines:
19         m = re.match(r'  File .*, line (\d+), in foo\n.*\n', line)
20         if m and int(m.group(1)) < 5:
21             print("Foo threw!")
22             sys.exit()
23     raise
24 else:
25     sys.stderr.write("foo did not throw!")

The question is: can I add some code logic between line 10-14, thus make the final code control flow can reach at line 21 , where Foo threw! 问题是:我可以在10-14行之间添加一些代码逻辑,从而使最终的代码控制流可以到达Foo threw!21Foo threw! got printed out ? 被打印出来了吗? Attention that, codes between line 1-10 and after line 14 can NOT be modified. 注意,不能修改第1-10行和第14行之间的代码。

I was tried to write another function to raise an exception, replace foo() with it, it didn't work since the if at line 20, which test against < 5 , "protect" the exception happened before line 5. 我试图编写另一个引发异常的函数,将其替换为foo() ,由于第20行的if< 5进行测试,“保护”异常发生在第5行之前,因此该函数不起作用。

No, because these lines: 不,因为这些行:

m = re.match(r'  File .*, line (\d+), in foo\n.*\n', line)
if m and int(m.group(1)) < 5

mean that the error must happen in lines 1-4 which come before foo , so it's not even possible if you add an error to the first line of foo . 意味着错误必须在1-4行前哪来发生foo ,所以如果你添加一个错误的第一行它甚至不能foo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM