【问题标题】:Better way to write nested exceptions in Python在 Python 中编写嵌套异常的更好方法
【发布时间】:2021-06-24 14:01:53
【问题描述】:
    try:
        return load(file)
    except FileNotFoundError:
        try:
            return load(otherfile)
        except FileNotFoundError:
            return None

如何写得更干净?我觉得必须有更好的方法来完成这个(我假设当其他两个文件失败时会加载第三个文件)

【问题讨论】:

  • for f in file_list: try: return load(f) except ......?

标签: python exception try-except


【解决方案1】:

如果你有很多文件,你可以把它放到循环中:

file_list = [file, otherfile]
for f in file_list:
    try:
        return load(f)
    except FileNotFoundError:
        continue
return None

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    相关资源
    最近更新 更多