[Tutor] Callbacks and exception handling
Steven D'Aprano
steve at pearwood.info
Fri Aug 13 04:09:54 CEST 2010
On Fri, 13 Aug 2010 11:56:31 am Pete wrote:
> Hi,
>
> I've been writing some code which uses callbacks. I have not used
> callbacks much before, but it does not seem too difficult so far.
>
> One thing though - I noticed that when an exception is raised in the
> callback function, that exception doesn't actually "show up" in the
> calling program.
>
> Two questions:
>
> 1) Theoretically - why is this? I guess I've seen callback functions
> a little like subroutines, therefore it seems intuitive that an
> exception would be propagated up to the calling routine.
They are, unless the calling function explicitly catches and subpresses
the exception.
> 2) How can you catch an exception in the callback function?
The same way you catch an exception anywhere: with a try...except block.
If you are writing a callback function, and want to catch your own
exception:
def callback():
try:
do_stuff_here
except (KeyError, ValueError, TypeError): # or whatever
pass
If you are writing the calling function:
def caller(arg, callback):
do_something_with(arg)
try:
callback()
except (AttributeError, RecursionError): # or whatever
pass
By the way, don't be tempted to write a bare except clause:
try:
...
except:
...
There are very few reasons for such a thing, as they are too broad and
catch too many things, masking errors, preventing user keyboard
interrupts, etc. Avoid them.
--
Steven D'Aprano
More information about the Tutor
mailing list