exception handling for a function returning several values

Steven Bethard steven.bethard at gmail.com
Fri Feb 11 20:12:37 EST 2005


beliavsky at aol.com wrote:
> If a function that normally returns N values raises an exception, what
> should it return?

Depends on what you want to do with the result of the function.

> N values of None seems reasonable to me, so I would
> write code such as
> 
> def foo(x):
>     try:
>        # code setting y and z
>        return y,z
>     except:
>        return None,None
> 
> y,z = foo(x)

You almost never want a bare except.  What exception are you catching?

My suspicion is that the code would be better written as:

def foo(x):
     # code settying y and z
     return y, z

try:
     y, z = foo(x)
except FooError:
     y, z = None, None

but I'm not sure if you really want y and z to be None if foo fails. 
What do you do with y and z?

Steve



More information about the Python-list mailing list