可以检测到我是否在Python中的'except'子句中吗?

2024-03-29 08:44:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要的是:

try:
    print inExceptClause()
    1/0
except Exception:
    print inExceptClause()
print inExceptClause()

。。。打印出来:

False
True
False

Tags: falsetrueexceptionprinttryexceptinexceptclause
2条回答

sys.exc_info()

This function returns a tuple of three values that give information about the exception that is currently being handled. (...) If no exception is being handled anywhere on the stack, a tuple containing three None values is returned.

另请参见以下问题:

Python 3 traceback fails when no exception is active
Raising exceptions when an exception is already present in Python 3

我想你走错方向了。您的“用例”似乎可以从代码中的多个点调用函数,有时可以从异常处理程序中调用。在这个函数中,您想知道是否抛出了异常,对吗?你知道吗

关键是,您不希望在一个对调用代码不了解(或者应该不了解)的函数中使用这种逻辑。。。理想情况下,您的大多数函数都不会有。你知道吗

也就是说,您可能希望执行该函数,但只是部分执行。所以我建议两种选择之一:

  1. 将函数拆分为多个函数:一个函数具有额外的功能,并将依次调用另一个具有可重用功能的函数。只要调用你需要的函数,当你需要的时候。

  2. 向函数中添加一个参数:一个简单的布尔值可能足以插入或排除该函数的一小部分。

现在,这并不是你问题的答案,但我觉得你从错误的角度看待你的问题。。。因此提出了上述建议。你知道吗

相关问题 更多 >