Re: arbitrary exception handlers

Guido.van.Rossum@cwi.nl
Wed, 22 Feb 1995 12:39:17 +0100

> At present it seems I can only catch an exception if I do something
> like this
>
> try:
> a_statement_that_might_cause_exception_E
> except E:
> ...
>
> When I would really like to set up a catcher like this,
>
> on except E do
> ...
>
> lots_of_statements_any_one_of_which_may_cause_exception_E
>
> Is there any way to do this in Python - to set up a kind of global
> exception catcher. Note that I cannot do something like,
>
> try:
> lots_of_statements_any_one_of_which_may_cause_exception_E
> except E:
> ...
>
> because some of the statements are in different modules/classes to
> the others.

I'm not sure I understand your problem. If you call code in another
module from within a try-except statement, your exception handler will
still be invoked, e.g.

# module A
def f(): raise RuntimeError

and

# module B
import A
try:
A.f()
except RuntimeError:
print 'Got it'

This will print 'Got it'.

However, I feel that what you really want is to install an exception
handler that gets called after the code that installed it is gone,
like

# module A
def f():
on RuntimeError: print 'Got it'

and

# module B
import A
A.f()
raise RuntimeERror

This is not possible in Python. It smells of signal handling though
-- maybe you can do something with the signal module?

If I still misunderstand what you want, perhaps you can give another
example?

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>