python - 如何清除Python中的异常状态

标签 python try-except

我有一个围绕 API 调用的 try/except block 。在我看来,一旦出现异常,该异常之后的所有有效尝试案例都会看到相同的异常。我能够让它工作的唯一方法是重新启动我的 Python 脚本。我用 google 搜索了一下,发现 PyErr_clear() 但那是针对 C-API 的。我可以从普通的 Python 中调用一些可以清除异常状态的东西吗?

这是我正在做的事情的基本想法:

def get_and_print_data(key):
   try:
      data = get_data_from_some_3rd_party_api(key)
   except Exception as ex:
      print("Failed to get data for",key,": ",str(ex))
      return

   print("data=",data)

然后在主要部分我有

get_and_print_data("Valid Key")     ## This works
get_and_print_data("INvalid Key")   ## This gets exception, as expected
get_and_print_data("Valid Key")     ## This and all subsequent calls to get_and_print_data() fail with the same exception.

最佳答案

举个例子来说明为什么我认为是第 3 方 API 存在问题:

def get_data_from_some_3rd_party_api(key):
    if key == "Valid Key":
        return "This is some good data."
    else:
        raise ValueError("Invalid Key")

def get_and_print_data(key):
   try:
      data = get_data_from_some_3rd_party_api(key)
   except Exception as ex:
      print("Failed to get data for",key,": ",str(ex))
      return
   print("data=",data)

get_and_print_data("Valid Key")     ## This works
get_and_print_data("INvalid Key")   ## This gets exception, as expected
get_and_print_data("Valid Key")     ## This works

尝试在本地运行此命令,您应该会看到后续的有效 key 仍然有效。

关于python - 如何清除Python中的异常状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52669978/

相关文章:

python if/else 和 try/except 组合无冗余

python - 在单元测试中模拟解析器对象

python - 使用 easy_install 安装 pip

python - OpenCV 3.4.0中传递给FlannBasedMatcher的参数 “algorithm”是什么意思?

python - 其他选项而不是使用 try-except

python尝试除了不工作

python - 如何定义多个错误处理语句?

python - 输入图像大小不为8时如何实现dct?

python - 为什么我的不同实例变量在 python 中链接在一起

python - 带有空 except 代码的 Try-except 子句