>>> myexc = "My exception string"
>>> try:
...     raise myexc
... except myexc:
...     print 'caught'
...
caught



>>> raise myexc
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
My exception string



>>> myexc = 'My exception string'
>>> try:
        raise myexc
    except myexc:
        print 'caught'

Warning (from warnings module):
  File "__main__", line 2
DeprecationWarning: raising a string exception is deprecated
caught



# class exc.py 

class General:            pass
class Specific1(General): pass
class Specific2(General): pass

def raiser0():
    X = General()          # Raise superclass instance.
    raise X

def raiser1():
    X = Specific1()        # Raise subclass instance.
    raise X

def raiser2():
    X = Specific2()        # Raise different subclass instance.
    raise X

for func in (raiser0, raiser1, raiser2):
    try:
        func()
    except General:        # Match General or any subclass of it.
        import sys
        print 'caught:', sys.exc_info()[0]

C:\python> python classexc.py
caught: __main__.General
caught: __main__.Specific1
caught: __main__.Specific2



class General(Exception): pass
class Specific1(General): pass
class Specific2(General): pass



# stringexc.py

General   = 'general'
Specific1 = 'specific1'
Specific2 = 'specific2'

def raiser0(): raise General
def raiser1(): raise Specific1
def raiser2(): raise Specific2

for func in (raiser0, raiser1, raiser2):
    try:
        func()
    except (General, Specific1, Specific2):     # Catch any of these.
        import sys
        print 'caught:', sys.exc_info()[0]

C:\python> python stringexc.py
caught: general
caught: specific1
caught: specific2



# mathlib.py

divzero = 'Division by zero error in library'
oflow   = 'Numeric overflow error in library'
...
def func():
    ...
    raise divzero



# client.py

import mathlib
...
try:
    mathlib.func(...)
except (mathlib.divzero, mathlib.oflow):
    ...report and recover...



# mathlib.py

divzero = 'Division by zero error in library'
oflow   = 'Numeric overflow error in library'
uflow   = 'Numeric underflow error in library'



# client.py

try:
    mathlib.func(...)
except (mathlib.divzero, mathlib.oflow, mathlib.uflow):
    ...report and recover...



# client.py

try:
    mathlib.func(...)
except:                           # Catch everything here.
    ...report and recover...



# mathlib.py

class NumErr(Exception): pass
class Divzero(NumErr): pass
class Oflow(NumErr): pass
...
def func():
    ...
    raise DivZero()



# client.py

import mathlib
...
try:
    mathlib.func(...)
except mathlib.NumErr:
    ...report and recover...



# mathlib.py

...
class Uflow(NumErr): pass



>>> import exceptions
>>> help(exceptions)
...lots of text omitted...



try:
    action()
except StandardError:
    ...handle Python errors...
except:
    ...handle user exceptions...
else:
    ...handle no exception case...



>>> class MyBad: pass

>>> raise MyBad()

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    raise MyBad()
MyBad: <__main__.MyBad instance at 0x00BB5468>



>>> class MyBad:
...     def __repr__(self):
...         return "Sorry--my mistake!"
... 
>>> raise MyBad()

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    raise MyBad()
MyBad: Sorry--my mistake!



>>> class MyBad(Exception): pass
>>> raise MyBad()

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    raise MyBad()
MyBad

>>> class MyBad(Exception): pass
>>> raise MyBad('the', 'bright', 'side', 'of', 'life')

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    raise MyBad('the', 'bright', 'side', 'of', 'life')
MyBad: ('the', 'bright', 'side', 'of', 'life')



>>> class FormatError:
...     def __init__(self, line, file):
...         self.line = line
...         self.file = file
...
>>> def parser():
...     # when error found
...     raise FormatError(42, file='spam.txt')
... 
>>> try:
...     parser()
... except FormatError, X:
...     print 'Error at', X.file, X.line
...
Error at spam.txt 42



>>> formatError = 'formatError'

>>> def parser():
...     # when error found
...     raise formatError, {'line':42, 'file':'spam.txt'}
...
>>> try:
...     parser()
... except formatError, X:
...     print 'Error at', X['file'], X['line']
...
Error at spam.txt 42



class FormatError:
    def __init__(self, line, file):
        self.line = line
        self.file = file
    def logerror(self):
        log = open('formaterror.txt', 'a')
        print >> log, 'Error at', self.file, self.line

def parser():
    raise FormatError(40, 'spam.txt')

try:
    parser()
except FormatError, exc:
    exc.logerror()



formatError = "formatError"

def logerror(line, file):
    log = open('formaterror.txt', 'a')
    print >> log, 'Error at', file, line

def parser():
    raise formatError, (41, 'spam.txt', logerror)

try:
    parser()
except formatError, data:
    data[2](data[0], data[1])        # Or simply: logerror()



raise KeyError()              # Normal form: raise an instance
raise KeyError, KeyError()    # Class, instance: uses instance
raise KeyError                # Class: an instance will be generated
raise KeyError, "bad spam"    # Class, arg: an instance will be generated

try:
    ...
except KeyError, X:
    ...
 
