error handling in Python

Diez B. Roggisch deetsNOSPAM at web.de
Wed May 5 13:57:57 EDT 2004


beliavsky at aol.com wrote:

> that if successful returns two Numeric arrays, of dates and prices. I
> am unsure what to return if read_data is unsucessful. Since a
> successful function call returns a list of length two, I could return
> a list of length one if there is a problem, so that [-1] is returned
> if the file does not exist, [-2] if the dates are invalid, etc. After
> calling the function, I could check the len of the result to detect
> problems. This seems workable but ad-hoc.

are you aware of the multiple assignment capabilities of python? You can do
it like this:

def foo():
   a = compute_me()
   b = me_too()
   return a,b

s, t = foo()

so basically you can simply return always three values: your results, and an
error value. The value then is checked.

> I do NOT want to use the try/except idiom to stop the program if there
> is a problem reading data.

Why not? exceptions are definetely the best way (at least in python) to deal
with error conditions. You should utilize them. And they don't stop the
program - only if you want them to. The big advatage is that the programmer
becomes aware of an error condition, while with your approach she can
easily forget to check for the error.


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list