Is this the *right* way of exception handling?
Alex Martelli
aleaxit at yahoo.com
Fri Aug 3 08:18:44 EDT 2001
"Piotr Legiecki" <piotrlg at sci.pam.szczecin.pl> wrote in message
news:9kdr21$rao$1 at zeus.man.szczecin.pl...
> Hi
>
> I wonder if the way I use exceptions is the right way or very problematic
> one (anyway it works of course).
You're using a string exception: this has not been the right way for
a while in Python -- use a class instead.
> I have one class and fill it with a data. If data are wrong i raise my
> exception:
>
> class A:
> my_exception='my_exception'
> .......
Change to:
class A:
class my_exception(Exception): pass
....
> def f(self,a):
> if a !=0
> raise my_exception, 'a must be 0'
I think you mean
raise self.my_exception, 'a must be 0'
or
raise A.my_exception, 'a must be 0'
because unqualified my_exception can't possibly work here.
> #!!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?
sys.exit() raises SystemExit, so there's not all that much difference
between calling it and raising something else. Normally, a raise without
parameters, re-raising the same exception you just caught, is simplest.
>
> def main():
> ...
> use some resources, open files etc
>
> f1()
>
> close resources, files etc
Make sure main uses:
try: f1()
finally:
close_whatever()
so that close_whatever is called no matter what.
Alex
More information about the Python-list
mailing list