Newbie naive question ... int() throws ValueError

Chris Angelico rosuav at gmail.com
Fri May 11 02:10:41 EDT 2012


On Fri, May 11, 2012 at 3:55 PM, John Terrak <john.terrak at gmail.com> wrote:
> I couldnt find anywhere in the documentation that int() can throw a ValueError.
> I checked the "The Python Language Reference", and the "The Python
> Standard Library " to no avail.
> Did I missed something?

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. In the case of int(), that would mean that you
catch ValueError if you're taking arbitrary strings from the user and
want integers (and then you could handle the ValueError by using a
default, for instance); but if you're writing a function that's
documented as taking a number as a parameter, let the exception go up
to the caller.

If it helps, think of all Python's exceptions as deriving from
RuntimeException - anything can happen, worry only about what really
worries you :)

> Thanks for your help - and sorry again for such a naive question.

It's a perfectly legitimate question, and you clearly did read the
docs before asking. Nothing to apologize for there!

Chris Angelico



More information about the Python-list mailing list