On 5/11/2012 1:55 AM, John Terrak 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?

To add to Chris' answer:

If the domain of a function is truly all Python objects, it cannot raise an error. I believe id(x) is such an example.

Even if the domain is intended to be all Python objects, you cannot be sure if the function uses any special method defined on the object or its class. For examples, type(x) *should* always work, but I would not be surprised if a buggy __getattribute__ method or buggy metaclass could result in an exception instead.

If the arguments for a function include a function, for example map(f, 'abc'), then the passed function can raise any exception and hence the called function will pass along the exception unless, unusually, it catches it.

As to your specific question, if the domain of a function is a subset of types and values of allowed types, then you should expect that it can raise either TypeError or ValueError.
If the domain

So here is the question - if it is not in the documentation - how does
one find out the
exceptions that are thrown by a constructor, a method or a function?

One way is to try specific examples, as you did. Following what Chris said, especially do that for bad input whose exception you want to catch. Sometimes this is faster than trying to find the answer in the doc, and it gives the actual answer rather than the intended answer.

Example:  int("not_an_int")
int("not_an_int")
Traceback (most recent call last):
   File "<stdin>", line 1, in<module>
ValueError: invalid literal for int() with base 10: 'not_an_int'

Some strings are legal input, hence not a TypeError, but not all, hence ValueError.

From what I gathered:
class int(object):
   """ int(x[, base]) ->  integer

   Convert a string or number to an integer, if possible.  A floating point
   argument will be truncated towards zero (this does not include a string
   representation of a floating point number!)  When converting a string, use
   the optional base.  It is an error to supply a base when converting a
   non-string.  If base is zero, the proper base is guessed based on the
   string content.  If the argument is outside the integer range a
   long object will be returned instead. """

'error' should say 'TypeError' as it is a TypeError to provide the wrong number of args. However, the current 3.3 manual entry is more accurate and informative, starting with the signature.

--
Terry Jan Reedy

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

Reply via email to