Form without except: try: statements finally: statements Form with except: try: statements except [type [as value]]: statements [except [type [as value]]: statements]* [else: statements] [finally: statements]

In [20]:
class cello :
    pass

strings = ('"hello"',
           'hello',
           '"hello" + 2',
           '"hello"[5]',
           '{"hello": 0}["hi"]',
           'cello.pitch',
           'open("hello.txt")')

from random import choice

try:
    string = choice(strings)
    print(string)
    exec(string)
finally:
    print('Output in any case')


"hello" + 2
Output in any case
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-d86dd5e8ce44> in <module>()
     12     string = choice(strings)
     13     print(string)
---> 14     exec(string)
     15 finally:
     16     print('Output in any case')

<string> in <module>()

TypeError: Can't convert 'int' object to str implicitly

In [23]:
class cello :
    pass; exec(cello.pitch)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-0e47ad07a9fe> in <module>()
----> 1 class cello : pass; exec(cello.pitch)

<ipython-input-23-0e47ad07a9fe> in cello()
----> 1 class cello : pass; exec(cello.pitch)

NameError: name 'cello' is not defined

In [ ]:
strings = ('"hello"',
           'hello',
           '"hello" + 2',
           '"hello"[5]',
           '{"hello": 0}["hi"]',
           'class cello : {} ; cello.pitch',
           'open("hello.txt")')

from random import choice

try:
    string = choice(strings)
    print(string)
    exec(string)
except NameError:
    print
    print('NameError!')
except TypeError as e:
    print('TypeError!')
    print(e)
except (IndexError, KeyError):
    print('IndexError or KeyError!')
except:
    print('Any other error...')
else:
    print('All good, no error.')
finally:
    print('Output in any case')

In [ ]:
try:
    hello
except NameError:
    try:
        'hello'[5]
    except IndexError:
        try:
            {"hello": 0}["hi"]
        except KeyError as e:
            raise ZeroDivisionError from e

In [ ]:
try:
    1 / 0
except ZeroDivisionError:
    raise ZeroDivisionError('I shall not divide by 0!') from None