Raising an exception in the caller's frame

Thomas Heller theller at python.net
Fri Mar 21 14:12:06 CET 2003


Alex Martelli <aleax at aleax.it> writes:

> Thomas Heller wrote:
>    ...
> > 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().
> 
> Yes, your purpose is very clear to me and I agree there _should_
> be a way to achieve it, but I can't think of one.
> 
> 

The best I came up with so far is to *return* an exception
instead of raising it, and do a typecheck in the caller:

def check_result(value):
    if somecondition(value):
        return ValueError(value) # or whatever
    return value

def do_some_work():
    value = dosomething()
    result = check_result(value)
    if isinstance(result, Exception):
        raise result
    return result

Thomas




More information about the Python-list mailing list