[Tutor] How to return a list in an exception object?
Alan Gauld
alan.gauld at btinternet.com
Wed Jun 17 20:35:18 CEST 2015
On 17/06/15 13:49, David Aldrich wrote:
> I have a function that compares a set of files with a reference set of files.
> All files are compared and then, if any differences were found, an exception
> is raised:
That's a pretty horrible way to deal with things. Exceptions should be
used for exceptional circumstances not as a way of passing data around
for a perfectly predictable circumstance.
Why not just pass back the list and if its empty you know it succeeded.
And since an empty list if False in a boolean sense you can even use it
like:
if check_results(): ...
when you don't care about the result content.
> class Error(Exception): pass
>
> def check_results(file_list):
>
> <snip>
>
> if isDifferent:
> raise Error('One or more result files differ from the reference result files')
Is there any reason why you want to use an exception?
Is there an API that require it or something?
Its certainly possible to do it, but its a pretty horrible
idiom. Functions should return any data as a return value
not tucked inside an exception.
Valid exceptions would be things like incompatible file
types (being asked to compare data values to jpegs or mp3s
for example) or, just possibly, mismatching file sets
(different numbers say).
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list