Exception as the primary error handling mechanism?
clp2 at rebertia.com
Wed Jan 6 02:01:02 CET 2010
On Tue, Jan 5, 2010 at 3:51 PM, Phlip <phlip2005 at gmail.com> wrote:
> Peng Yu wrote:
>> Otherwise, could some python expert explain to me why exception is
>> widely used for error handling in python? Is it because the efficiency
>> is not the primary goal of python?
> It's not about efficiency, it's about making assumptions for the
> programmer about what kind of rigor they need.
> Why can't int('nonnumeric') return None?
Errors should never pass silently.
Unless explicitly silenced.
-- The Zen of Python (http://www.python.org/dev/peps/pep-0020/)
Better to throw an exception and ensure the case is specifically dealt
with one way or another than to silently return an error flag result
which may only delay the error until later in the program, making it
harder to debug. Is it that much of a burden to write and use the
small function that does what you want?
Heck, you can even write it inline and dispense with the function if you want:
try: foo = int(bar)
except ValueError: foo = None
Quibbling over a mere one more line of code (or writing one short
function) seems a bit petty.
> (A related question - why can't I just go 'if record = method(): use
> (record)'. Why extra lines just to trap and assign the variable before
> using it?)
I believe that's disallowed so as to prevent the subtle bugs seen in C
code which result from when someone makes a typo and omits the second
"=" in their `if foo == bar():` test.
More information about the Python-list