error handling in Python

John Roth newsgroups at jhrothjr.com
Wed May 5 16:55:41 EDT 2004


<beliavsky at aol.com> wrote in message
news:3064b51d.0405050741.43d11aa0 at posting.google.com...
> Suppose I have a function
>
> def read_data(xfile):
>     # code here to read dates and prices
>     return dates,prices
>
> that if successful returns two Numeric arrays, of dates and prices.

It looks like you're still thinking in Fortran. It's probably going to
be easier all around to return one list of two element tuples.

> 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.



> I do NOT want to use the try/except idiom to stop the program if there
> is a problem reading data.
>
> In Fortran I would write a subroutine with calling sequence
>
> call read_data(xfile,dates,prices,ierr)
>
> where ierr would be checked upon return for nonzero values.

The basic question is: what do you want to do with an error?
That conditions how you want to handle it. Do you want to print
an error message and quit? Print an error message and continue
with the next batch? Fake up a return so the rest of the program
continues as if nothing was wrong?

John Roth





More information about the Python-list mailing list