在 Python 中编写嵌套异常的更好方法
Better way to write nested exceptions in Python
try:
return load(file)
except FileNotFoundError:
try:
return load(otherfile)
except FileNotFoundError:
return None
如何写的更干净?我觉得必须有更好的方法来完成这个(我假设当其他两个文件失败时会有第三个文件加载)
如果你有很多文件,你可以把它放到循环中:
file_list = [file, otherfile]
for f in file_list:
try:
return load(f)
except FileNotFoundError:
continue
return None
try:
return load(file)
except FileNotFoundError:
try:
return load(otherfile)
except FileNotFoundError:
return None
如何写的更干净?我觉得必须有更好的方法来完成这个(我假设当其他两个文件失败时会有第三个文件加载)
如果你有很多文件,你可以把它放到循环中:
file_list = [file, otherfile]
for f in file_list:
try:
return load(f)
except FileNotFoundError:
continue
return None