Exceptions

Catch

try:
    self.open()
except HTTPError as e:
    print http error: ' + str(e)

Chained

python 3 only:

try:
    v = {}['a']
except KeyError as e:
    raise ValueError('failed') from e

Unknown

…to catch exceptions of an unknown, try:

try:
    somecode()
except Exception as e:
    print e

or:

try:
    somecode()
except:
    print sys.exc_info()[0]

Finally

Note for python/jython 2.1 see Note below…

Try..Finally:

try:
    f = file('poem.txt')
    for line in f:
        print line,
finally:
    f.close()

Note

PEP 341: Unified try/except/finally Until Python 2.5, the try statement came in two flavours. You could use a finally block to ensure that code is always executed, or one or more except blocks to catch specific exceptions. You couldn’t combine both except blocks and a finally block*

To solve this problem nest a try, except within a try, finally e.g:

cursor = None
try:
    try:
        cursor = somecode()
    except Exception as e:
        print e
finally:
    if cursor != None:
        c.close()

Throw

To throw an exception:

class SyncError(Exception):

    def __init__(self, value):
        Exception.__init__(self)
        self.value = value

    def __str__(self):
        return repr('{}, {}'.format(self.__class__.__name__, self.value))
try:
    raise SyncError(2*2)
except SyncError as e:
    print 'My exception occurred, value:', e.value

Exceptions

raise NotImplementedError("Village, has_school")

Rethrow

raise

If no expressions are present, raise re-raises the last exception that was active in the current scope:

raise

Stack Trace

import traceback
try:
    raise Exception("print exception!")
except:
    print traceback.format_exc()