如果没有返回异常,则传递异常并引发错误的方法
Way to pass exception and raise error if no exception returned
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
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