从函数中捕获异常

catch a exception from a function

我有一个函数 'zero',我无法更改它或添加行。

def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

def main():
   zero(10,5)
   zero(10,0)

在主函数中我想调用零函数并知道该函数是否调用了异常。

您可以 return 除法的结果,或使用以下异常:

def zero(a, b):
    try:
        num = a / b
    except:
        num="cannot divide by zero"
    return num

这将允许您在主函数中比较结果并确定是否调用了异常。

考虑到您不能以任何方式更改 zero() 的限制(这是正确的做法),那么您可以重定向 stdout 并解析输出。

import sys
import io


def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

if __name__ == '__main__':
    old_stdout = sys.stdout
    for x, y in [(5, 0), (10, 2), (10, 0)]:
        new_stdout = io.StringIO()
        sys.stdout = new_stdout
        zero(x, y)
        result = new_stdout.getvalue().strip()
        if result:
            print(f'Division {x}/{y} raise an error:{result}', file=old_stdout)
    sys.stdout = old_stdout

输出

Division 5/0 raise an error:cannot divide by zero
Division 10/0 raise an error:cannot divide by zero

这是一个奇怪的要求,因为函数总是 returns None,因为 num 是局部变量而函数不会 return 它。因此,您甚至无法通过在函数中添加 global 语句的情况下使用全局变量 num 来确定存在异常。

这种方法会奏效,虽然我对这个问题的看法很差:

def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

def print(error):
    raise ValueError(error)

>>> zero(10,5)
>>> zero(10,0)
Traceback (most recent call last):
  File "<pyshell#1>", line 3, in zero
    num = a / b
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    zero(10,0)
  File "<pyshell#1>", line 5, in zero
    print("cannot divide by zero")
  File "<pyshell#11>", line 2, in print
    raise ValueError(error)
ValueError: cannot divide by zero

函数 zero() 的编码非常糟糕,强迫您原封不动地使用它在我看来几乎没有什么教育意义,除了可能让大家明白,裸露的 except 子句是一个坏主意。

这个答案在精神上与@buran 的答案相似。它们都涉及更改 print() 的行为以在函数之外传递您想要的信息。