# nestexc.py

def action2():
    print 1 + [  ]           # Generate TypeError.

def action1():
    try:
        action2()
    except TypeError:        # Most recent matching try
        print 'inner try'

try:
    action1()
except TypeError:            # Here, only if action1 reraises.
    print 'outer try'

% python nestexc.py
inner try



try:
    try:
        action2()
    except TypeError:      # Most recent matching try
        print 'inner try'
except TypeError:          # Here, only if nested handler reraises.
    print 'outer try'



>>> try:
...     try:
...         raise IndexError
...     finally:
...         print 'spam'
... finally:
...     print 'SPAM'
...
spam
SPAM
Traceback (most recent call last):
  File "<stdin>", line 3, in ?
IndexError



# except-finally.py

def raise1():  raise IndexError
def noraise(): return
def raise2():  raise SyntaxError

for func in (raise1, noraise, raise2):
    print '\n', func
    try:
        try:
            func()
        except IndexError:
            print 'caught IndexError'
    finally:
        print 'finally run'



% python except-finally.py

<function raise1 at 0x00BA2770>
caught IndexError
finally run

<function noraise at 0x00BB47F0>
finally run

<function raise2 at 0x00BB4830>
finally run

Traceback (most recent call last):
  File "C:/Python25/except-finally.py", line 9, in <module>
    func()
  File "C:/Python25/except-finally.py", line 3, in raise2
    def raise2():  raise SyntaxError
SyntaxError: None



while 1:
    try:
        line = raw_input()     # Read line from stdin.
    except EOFError:
        break                    # Exit loop at end of file
    else:
        ...process next line here...



class Found(Exception): pass

def searcher():
    if ...success...:
        raise Found()
    else:
        return

try:
    searcher()
except Found:              # Exception if item was found
    ...success...
else:                      # else returned: not found
    ...failure...



class Failure(Exception): pass

def searcher():
    if ...success...:
        return ...founditem...
    else:
        raise Failure()

try:
    item = searcher()
except Failure:
    ...report...
else:
    ...use item here...



try:
    ...run program...
except:                  # All uncaught exceptions come here.
    import sys
    print 'uncaught!', sys.exc_info()[0], sys.exc_info()[1]



# testdriver.py

import sys
log = open('testlog', 'a')
from testapi import moreTests, runNextTest, testName

def testdriver():
    while moreTests():
        try:
            runNextTest()
        except:
            print >> log, 'FAILED', testName(), sys.exc_info()[:2]
        else:
            print >> log, 'PASSED', testName()

testdriver()



def func():
    try:
        ...                # IndexError is raised in here
    except:
        ...                # But everything comes here and dies!

try:
    func()
except IndexError:         # Exception should be processed here
    ...



# exiter.py

import sys

def bye():
    sys.exit(40)             # Crucial error: abort now!

try:
    bye()
except:
    print 'got it'           # Oops--we ignored the exit
print 'continuing...'


% python exiter.py
got it
continuing...



mydictionary = {...}
...
try:
    x = myditctionary['spam']     # Oops: misspelled 
except:
    x = None                      # Assume we got KeyError.
...continue here with x...



try:
    ...
except (myerror1, myerror2):    # Breaks if I add a myerror3
    ...                         # Nonerrors
else:
    ...                         # Assumed to be an error



try:
    ...
except SuccessCategoryName:     # Okay if I add a myerror3 subclass
    ...                         # Nonerrors
else:
    ...                         # Assumed to be an error



>>> ex1 = 'The Spanish Inquisition'
>>> ex2 = 'The Spanish Inquisition'

>>> ex1 == ex2, ex1 is ex2
(True, False)



>>> try:
...    raise ex1
... except ex1:
...    print 'got it'
...
got it



>>> try:
...    raise ex1
... except ex2:
...    print 'Got it'
...
Traceback (most recent call last):
  File "<pyshell#43>", line 2, in <module>
    raise ex1
The Spanish Inquisition



>>> try:
        raise 'spam'
    except 'spam':
        print 'got it'
	
got it



>>> try:
        raise 'spam' * 8
    except 'spam' * 8:
        print 'got it'

Traceback (most recent call last):
  File "<pyshell#58>", line 2, in <module>
    raise 'spam' * 8
spamspamspamspamspamspamspamspam




















