Search code examples
pythonexceptionerror-handlingpygsheets

How to use custom exceptions from packages in your excepts clauses?


I have a script which uses the package pygsheets to upload a dataframe to Google sheets. If the dataframe is empty, the following error appears:

InvalidArgumentValue: provide either cells or values, not both

So, I have been trying to use a try-except structure to pass when the dataframe is empty, but raising an exception if any other error happens. The code is the following:

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

However, when I try to execute the lines above, it throws me the following errors:

NameError: name 'InvalidArgumentValue' is not defined

How could I solve it?


Solution

  • Assuming you imported pygsheets in the usual fashion

    import pygsheets
    

    your code should reference exceptions contained in that package using the usual syntax for referencing member classes of another package, like

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