[Tutor] functions: use return or exceptions?

Alex Hall mehgcap at gmail.com
Fri Sep 24 00:38:34 CEST 2010

Thanks for the responses. Up to now, despite using some Java and a lot
of Python, I have not even tried raising exceptions. I can see
situations where they would be useful, but was not sure if I should
use them as much as possible or just keep relying on the return codes
that I am used to. Sounds like either way works and, as was stated,
exceptions should be used in "exceptional" cases.

On 9/23/10, Luke Paireepinart <rabidpoobear at gmail.com> wrote:
> You should do both. Raise an exception in the exceptional case.
> My general pattern is to return None if no results exist, return the results
> if they do exist, and raise an exception if I couldn't perform the function.
> Eg. If I have a function that creates a list of users with a first name of
> bob, I'll return the users or None (or probably an empty list) but if the db
> connection is unsuccessful I'll let the exception it throws propagate back
> up from my function, or possibly trap and rethrow the exception.
> Or if a db connection error shouldn't matter to the calling function, I just
> won't re raise the exception.
> I may not actually do that in practice, depending on the implications, but
> that's my general idea usually.
> -----------------------------
> Sent from a mobile device with a bad e-mail client.
> -----------------------------
> On Sep 23, 2010, at 2:47 PM, Wayne Werner <waynejwerner at gmail.com> wrote:
>> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall <mehgcap at gmail.com> wrote:
>> Hi all,
>> A general coding question: is it better to use return(False) (or 0, or
>> -1, or whatever) or to raise whateverError("oops")? Are there cases
>> for each?
>> It depends on your prevailing philosophy - if you like the EAFP that
>> prevails in python, it's better to raise an error. Usually that indicates
>> that something has failed.
>> OTOH, a lot of people feel that using exceptions as control flow is bad
>> practice - they're exceptional so they should only arise in exceptional
>> case.
>> There may be performance issues, though I'm not familiar enough with that
>> yet.
>> just my two bits,
>> -Wayne
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor

Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

More information about the Tutor mailing list