Exceptions

Bjorn Pettersen BPettersen at NAREX.com
Tue Feb 4 16:41:44 EST 2003


> From: Tetsuo [mailto:member16943 at dbforums.com] 
>
> > class CorruptHardDiskError(Exception):
> >     pass
> >
> > def Pythagoras(a,b):
> >     raise CorruptHardDiskError, "Pythagoras is out"
> >
> > try:
> >     Pythagoras(18, "x")
> > except CorruptHardDiskError:
> >     print "Wow"
> > 
> 
> And where is the actual program that finds the hypotenuse? And why is
> "pass" needed?

Your program content goes in the try: clause of the try/except, either
directly or by calling a function. Above, Pythagoras(18, "x") is called
to do the work, but it raises a CorruptHardDiskError which is caught in
the except: clause.

The pass statement in the exception class indicates that you don't want
to override any behavior from its super class, Exception. You can of
course create classes that do more, e.g.:

class SyntaxError(Exception):
    def __init__(self, line, pos):
        Exception.__init__(self)
        self.line, self.pos = line, pos
        
    def __repr__(self):
        return 'SyntaxError:\n\n  %s\n  %s' % (self.line, ('
'*(self.pos-1))+'^')
    
    __str__ = __repr__
        
try:
    raise SyntaxError('asdfasdfasdf', 5)
except SyntaxError, e:
    print e

hth,
-- bjorn





More information about the Python-list mailing list