Newbie naive question ... int() throws ValueError

Chris Angelico rosuav at gmail.com
Fri May 11 23:21:14 EDT 2012


On Sat, May 12, 2012 at 5:34 AM, Devin Jeanpierre
<jeanpierreda at gmail.com> wrote:
> On Fri, May 11, 2012 at 2:10 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> Unlike in Java, a function's list of things it can throw isn't part of
>> its signature. Instead of trying to catch every possible exception,
>> it's generally best to simply let exceptions propagate unless you KNOW
>> you're expecting them.
>
> How am I supposed to know to expect them, if they are undocumented?
> Trial and error? That seems like a poor replacement for documented
> error conditions.

Expect exceptions any time anything goes wrong. Don't try to code to
prevent them.

Here's an example. Suppose you write a function that takes a number
and returns that many copies of your club's charter. (Yeah, pretty
stupid, but examples usually are!)

def charter(copies):
    return _chartertext * copies

Does this function need to catch any exceptions? No. Can that
expression throw exceptions? Totally! You might be given a non-number
(can't give "foo" copies); you might get a floating point (can't get
three-and-a-half copies); your charter text might have been replaced
with a pizza; the user might hit Ctrl-C right while it's copying; the
number might be so large that you run out of memory; all sorts of
things. But they're not your problems - they're your caller's
problems. If you caught all those exceptions, what would you do? You'd
have to signal the error conditions yourself, which probably means...
raising an exception.

There are times when you want to catch all exceptions, though.
Top-level code will often want to replace exception tracebacks with
error messages appropriate to some external caller, or possibly log
the exception and return to some primary loop. Otherwise, though, most
code will just let unexpected exceptions through.

This is one of those massively freeing leaps of thinking. Java binds
you to a bureaucracy of catching exceptions or declaring them (but
then still has RuntimeException - and I'm sure there've been MANY
programmers who just derive all their exceptions from that); Python
sets you free to care only about what you want to care about.

ChrisA



More information about the Python-list mailing list