Raising an exception in the caller's frame

Thomas Heller theller at python.net
Fri Mar 21 03:46:57 EST 2003


Jp Calderone <exarkun at intarweb.us> writes:

> On Thu, Mar 20, 2003 at 09:14:22PM +0100, Thomas Heller wrote:
> > Is there any way to raise an exception in the callers (parent) frame?
> > 
> 
>   I don't believe so (at least not without performing unspeakable evil).
> 
> > See the following code, I want the exception to be raised in the 
> > do_some_work function, without changing this function itself:
> > 
> > def check_result(value):
> >     if somecondition(value):
> >         raise ValueError
> >     return value
> > 
> > def do_some_work():
> >     value = dosomething()
> >     return check_result(value)
> > 
> 
>   Consider this alternate definition of do_some_work...
> 
>     def do_some_work():
>         value = dosomething()
>         try:
>             return check_result(value)
>         except Exception, e:
>             raise e
> 
>   I'm not sure I'd use this, though - it masks useful information about the
> real source of the exception.
>  If I might ask, why do you want to do this?

Hopefully I can explain it: check_result() is not the 'cause' of the
error, it's purpose is simply to detect the error. The 'exception'
really occurrs in dosomething().

The situation is similar to what is explained for the warn() function,
see the stacklevel parameter.  Maybe I should look into the warnings
module.

Thanks,

Thomas




More information about the Python-list mailing list