Exceptions - built-in and home-grown
Heiko Wundram
heikowu at ceosg.de
Mon Sep 17 16:39:00 EDT 2001
On Monday 17 September 2001 21:24, you wrote:
> The problem with ANY sort of processing in the exception init routine
> is that it will only process your own exceptions. If you want to catch
> all exceptions you will need to apply careful use of try/except - in
> which case you may as well do all the exception handling there.
Well, actually the exception itself should _never_ do any exception
handling/cleanup in the __init__ function. The __init__ function of an
exception should only be used to create the instance (such as putting in the
correct data, formatting the exception error-string, etc.)
An exception that is raised (C++/Java calls it throwing) is basically a class
instance (can be of any class, at the moment).
Secondly, an exception is in some way or another something like a
return-value (if you come from C or Perl, you'll know that a return-value
signals error conditions).
The funky thing about exceptions is that you don't have to pack each and
every call to e.g. subfunctions into something like the following (what you'd
do in C):
if( !(some_ptr = do_something(another_ptr)) )
{
<cleanupcode if this stage goes wrong>
return false
}
if( !(third_ptr = do_something_too(some_ptr)) )
{
<cleanupcode if this stage goes wrong>
return false
}
etc. etc. etc.
Exceptions allow you to pack all this into one smart piece.
try:
some = do_something(another)
third = so_something_too(some)
except BlaBlaException, inst:
<cleanupcode if one of the two stages goes wrong>
raise
What Exceptions also allow you to do is give names to the error conditions
that are signalled (like BlaBlaException).
do_something would then contain a line like the following:
raise BlaBlaException(<parameters that specify the specific type of BlaBla>)
(look at the example of IOError, the parameters that are passed in specify
what kind of IOError occurred, but all have in common that they are
I/O-Errors, and IOError, the exception class, doesn't attempt at any cleaning
up at all.)
The cleanup goes into the function that catches the error, if noone catches
it, there'll be no cleanup!
> Or have I missed something important?
If you have understood the above, you haven't. :)
--
Yours sincerely,
Heiko Wundram
More information about the Python-list
mailing list