To throw or to throw not?

Chris Rebert clp at rebertia.com
Thu Nov 13 20:26:01 EST 2008


On Thu, Nov 13, 2008 at 5:11 PM, Emanuele D'Arrigo <manu3d at gmail.com> wrote:
> I'm pondering on what is a bit of a philosophical dilemma.
> When should I throw an exception and when should I not?
>
> Suppose I have myFunc1() calling myFunc2() which in turn calls myFunc3
> ().
> Suppose myFunc3() has detected a problem. What should it do?
>
> Throw an exception, forcing myFunc2() to handle it and/or trigger
> another exception for myFunc1() to deal with? Or should it simply
> return a meaningful error code, for myFunc2() and myFunc1() to handle
> as an option but not forcing them to do so?

Depends on how serious the error is (e.g. str.find() returns -1 rather
than raising an exception if it can't find the substring), but 98% of
the time, you'll want to raise an exception; it's Pythonic, idiomatic,
and expected. You'd have to have a *really* good reason to use an
error value/code instead.
Python is not C, and despite what Joel has said On Software, error
codes generally suck.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Manu
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list