Why use Python's “else” clause in try/except block? [duplicate]

怎甘沉沦 提交于 2019-12-01 17:59:12

问题


Possible Duplicate:
Python try-else

I'm not seeing the benefit of it, at least based on the example I just read in Dive Into Python:

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
else:
    getpass = AskPassword

(http://www.diveintopython.net/file_handling/index.html)

Why couldn't you achieve the same effect with the shorter/simpler:

try:
    from EasyDialogs import AskPassword
    getpass = AskPassword
except ImportError:
    getpass = default_getpass

What am I missing?


回答1:


There isn't an advantage in the example, except possibly for style. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:

try:
    from EasyDialogs import AskPassword
    # 20 other lines
    getpass = AskPassword
except ImportError:
    getpass = default_getpass

and

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
else:
    # 20 other lines
    getpass = AskPassword

The second one is good when the except can't return early, or re-throw the exception. If possible, I would have written:

try:
    from EasyDialogs import AskPassword
except ImportError:
    getpass = default_getpass
    return False // or throw Exception('something more descriptive')

# 20 other lines
getpass = AskPassword



回答2:


I personally find it clearer in some situations. Naturally the greater deal of code should be ran when an exception does not occur. So in a way you are saying:

try:
    this_very_dangerous_call()
except ValueError:
    # if it breaks
    handle_value_error()
else:
    continue_with_my_code()
    # more code

Thus you are visually separating the exception handling code from the rest of the code. It's like saying: "Try this, if it breaks do something, if it doesn't [insert long explanation here]"



来源:https://stackoverflow.com/questions/14590146/why-use-pythons-else-clause-in-try-except-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!