Search code examples
pythonexceptioncoding-styleidioms

Why use Python's "else" clause in try/except block?


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?


Solution

  • 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