如何在excepts子句中使用程序包中的自定义异常?

时间:2019-07-05 13:55:59

标签: python exception error-handling pygsheets

我有一个脚本,该脚本使用pygsheets包将数据框上传到Google表格。如果数据框为空,则会出现以下错误:

InvalidArgumentValue: provide either cells or values, not both

因此,我一直试图在数据帧为空时使用try-except结构通过,但是如果发生任何其他错误,则会引发异常。代码如下:

try:
    pygsheets code
except InvalidArgumentValue:
    pass
except:
    raise Exception

但是,当我尝试执行以上代码行时,会引发以下错误:

NameError: name 'InvalidArgumentValue' is not defined

我该如何解决?

1 个答案:

答案 0 :(得分:1)

假设您以通常的方式导入了pygsheets

import pygsheets

您的代码应使用通常的语法引用该程序包中包含的异常,以引用另一个程序包的成员类,例如

try:
    pygsheets code
except pygsheets.InvalidArgumentValue:
    pass
except:
    raise Exception