【问题标题】:Can there be an else block statement in python try-except? [duplicate]python try-except中可以有else块语句吗? [复制]
【发布时间】:2017-06-26 21:41:11
【问题描述】:

我正在尝试编写订阅列表模块。所以,我有一个语句,根据用户的电子邮件 ID,可能会引发索引超出范围错误。如果是,我希望程序做某事,如果不是,我希望程序完全做其他事情。我该怎么办?目前,我有代码尝试添加所有用户而不考虑并使程序崩溃。我最理想的情况是这样的:

try:
    check_for_email_id.from_database
except IndexError:
    create.user_id.in_database
    user.add.to.subscribe_list

else:
    user.add.to.subscribe_list

我需要能够在此处添加一个块,如果没有IndexError,则省略“do something”部分并执行else 部分。 Python 是否为此提供了内置选项?我可以在 Try-Except 语句中使用 if-else 块吗?

另外,避免为user.add.to.subscribe_list 编写两次代码的好方法是什么?除了创建一个新的 user_add 函数?

【问题讨论】:

    标签: python django try-except


    【解决方案1】:

    是的,python try/except(else/finally) 语句中的else 正是为了:只有在没有例外的情况下你希望发生的事情:

    import random
    try:
        1 / random.randrange(2)
    except Exception as e:
        print(e)
    else:
        print('we succeeded!')
    finally:
        # always prints
        print('we just tried to do some division!')
    

    在回答你的第二个问题时,看起来你真正想要的是使用 finally 子句:

    try:
        check_for_email_id.from_database
    except IndexError:
        create.user_id.in_database
    finally:
        # this gets called if there was an error or not
        user.add.to.subscribe_list
    

    【讨论】:

    • 那么,为了避免代码冗余,这应该是一个不同的问题,还是我可以在这里期待答案?谢谢你的回答。这有帮助。
    • @Di437 如果你把它放在finally 子句中,没有else,如果有错误或没有错误,它将被调用。我将添加一个编辑来说明我的意思。
    猜你喜欢
    • 1970-01-01
    • 2013-01-13
    • 2011-04-08
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2013-04-10
    • 2022-01-04
    • 1970-01-01
    相关资源
    最近更新 更多