Welcome, guest | Sign In | My Account | Store | Cart

A million things can go wrong, and there are several ways to succeed. You want to check for the ways that can succeed and continue on as soon as one of them does. You want the non-local flow of control that exceptions provide, but you need it for both success and failure.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def doLoginAction(self):
    """Try to actually log the user in."""
    class PasswordAccepted(Exception): pass
    try:
        if check_password():        # This may raise KeyError.
            raise PasswordAccepted
        do_more_expensive_work()
        and_even_more_expensive_work()
        if check_other_password():  #  This may raise KeyError.
            raise PasswordAccepted
        raise KeyError
    except KeyError:
        self.setError("Invalid username or password.")
        return
    except PasswordAccepted:
        pass
    continue_successfully()
Created by Shannon -jj Behrens on Wed, 19 Jan 2005 (PSF)
Python recipes (4591)
Shannon -jj Behrens's recipes (19)

Required Modules

  • (none specified)

Other Information and Tasks