Is this the *right* way of exception handling?

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Fri Aug 3 20:12:34 EDT 2001


On Fri, 03 Aug 2001 12:21:59 +0200, Piotr Legiecki
<piotrlg at sci.pam.szczecin.pl> wrote:
>Hi
>
>I wonder if the way I use exceptions is the right way or very problematic
>one (anyway it works of course).
>
>I have one class and fill it with a data. If data are wrong i raise my
>exception:
>
>class A:
>  my_exception='my_exception'

The usual style is to make your exception a class inheriting from Exception,
and to put it at the top level (not nested in a class defn).  Then you have
access to all the usual class stuff like methods and instance variables.

Another possibility is to use python's ValueError, which is the standard thing
to raise if you get an argument with a bad value.

Or you could write

assert a == 0, 'a must be 0'

which has the added benefit that when your program is debugged you can run it
with -O and omit all those now redundant checks.  Unfortunately, python's
assertion mechanism is not well integrated with the exception mechanism, so
assertions that should really raise a ValueError will always raise an
AssertionError.  A possible third argument to 'assert'?

>.......
>  def f(self,a):
>     if a !=0
>	raise my_exception, 'a must be 0'

You probably meant 'self.my_exception' or 'A.my_exception' here.

>def f1()
>...
>  try:
>    x=A()
>     x.f(1)
>  except A.my_exception, val:
>    print 'wow, eror', val
>    #!!now, what to do here, i want to stop my program, but should clean
>     something (close files etc) before, so sys.exit() is not a good idea
>     another raise?
>
>def main():
>...
>  use some resources, open files etc
>
>  f1()
>
>  close resources, files etc

Files and other resources should generally be freed at the same level they
were allocated.  So if you opened the files in main(), you should put your try
except around f1() and close them there.  You could also use destructors
(__del__) to automatically free resources, but it's risky for anything that
has to be done in a certain order.

If your exception handler doesn't resolve the error by some other means, it
should reraise the exception (after freeing resources) to let the caller know
the error condition still holds.  You can do that with a plain 'raise'
statement with no args.  Printing an error message and quitting is a form of
resolving the error, but you should generally only do that at the top level
(in fact, python will automatically print an error message and exit if it
reaches there, but it may not be the msg you want).



More information about the Python-list mailing list