Exception handling in Python follows a similar pattern to many other languages wit this construct. The statements with exception handling are contained in a try
block, followed by one or more except
blocks. The except
keyword is analogous to catch
in some other languages.
The body of the try
block is executed up to and including whatever statement raises (throws) an exception. At that point, the first except clause with an associated type that either matches, or is a supertype of, the exception raised will execute.
If no except clause matches, execution will exit the current scope and the process will continue back up the stack until the exception is handled or program execution terminates.
Regardless of whether the exception is caught at the current execution level, the optional finally
clause will execute if present. The finally
clause will also execute if no exception is raised and is ideally suited for resource cleanup.
If no exception is raised, optional else
block will be executed. The idea of an else
block in exceptions is less common and designed to limit the contents of the try
block, such that the types of exceptions being tested are quite explicit.
>>> characters = {'hero': 'Othello', 'villain': 'Iago', 'friend': 'Cassio'} >>> def get_char(role): ... try: ... name = characters[role] ... except KeyError, e: ... result = 'This play has no %s' % role ... else: ... result = '%s is the %s' % (name, role) ... finally: ... result += ' and it\'s a great play' ... return result ... >>> get_char('champion') "This play has no champion and it's a great play" >>> get_char('friend') "Cassio is the friend and it's a great play"