Raising an exception in the caller's frame

Thomas Heller theller at python.net
Fri Mar 21 21:30:49 CET 2003


logistix at zworg.com (logistix) writes:

> Thomas Heller <theller at python.net> wrote:
> > 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
> 
> Aren't you just really trying to assert?
> 
> def do_some_work():
>     value = dosomething()
>     assert somecondition(value), "Failed somecondition test!"
>     return value

No, I want check_result also to return meaningful results.
This includes returning something else maybe calculated from 'value'.

It seems I should explain the context better:

do_some_work is, for example, a win32 api function wrapped in a Python
callable. These functions tend to not raise exceptions, but sometimes
signal in return values that the call has failed.

The goal of the check_result() function is to check for these invalid
return values and raise an exception for them, and for valid return
values return something useful (possibly computed by using 'value').

Example:

The CreateWindowEx api function returns a window handle or NULL if it
fails.  The RegOpenKeyEx function returns an error code if it fails or
zero otherwise.

The check_result() function for CreateWindowEx would look like this:

def check_result(handle):
    if handle == 0:
        raise WindowsError(GetLastError())
    return Window(handle)

and for RegOpenKeyEx this would be used:

def check_result(code):
    if value == 0:
        return None
    raise WindowsError(code)

Thomas




More information about the Python-list mailing list