gpt4 book ai didi

python - 如果没有返回异常,则传递异常并引发错误的方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:39:36 24 4
gpt4 key购买 nike

def create_spreadsheet_with_api(connection, filename):
try:
connection.open(filename)
if (no exception):
raise exception file already exists
if (there exception):
connection.create(filename)

使用使用 google api 的 pygsheets 库,我正在尝试创建具有给定名称的电子表格,如果它不存在的话。

我收到异常 pygsheets.exceptions.SpreadsheetNotFound:

所以我需要像反向异常这样的东西,或者如果有更好的实践在 python 中做到这一点,我们将非常感谢您的建议。

最佳答案

try 子句有一个 else 部分,如果没有引发异常则执行该部分(名称相似,但与众所周知的 if-else 完全无关)。所以

def create_spreadsheet_with_api(connection, filename):
try:
connection.open(filename)
except FileNotFoundError:
connection.create(filename)
else:
raise FileAlreadyExistsError

关于python - 如果没有返回异常,则传递异常并引发错误的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com