1.

What is the difference between TypeError and ValueError?

Answer»

An exception is a type of run time error reported by a Python interpreter when it encounters a situation that is not easy to handle while executing a certain statement. Python’s library has a number of built-in exceptions defined in it. Both TypeError and valueError are built-in exceptions and it may at times be confusing to understand the reasoning behind their usage.

For EXAMPLE, int(‘hello’) raises ValueError when one would expect TypeError. A closer look at the documentation of these exceptions would clear the difference.

>>> int('hello') Traceback (most recent call last):  File "<pyshell#26>", line 1, in <module>    int('hello') ValueError: invalid literal for int() with base 10: 'hello'

Passing arguments of the WRONG type (e.g. passing a list when an int is expected) should result in a TypeError which is also RAISED when an operation or function is applied to an object of inappropriate type.

Passing arguments with the wrong value (e.g. a number outside expected BOUNDARIES) should result in a ValueError. It is also raised when an operation or function receives an argument that has the RIGHT type but an inappropriate value.

As far as the above case is concerned the int() function can accept a string argument so passing ‘hello’ is not valid hence it is not a case of TypeError. Alternate signature of int() function with two arguments receives string and base of number system

int(string,base) >>> int('11', base=2) 3

Second argument if ignored defaults to 10

>>> int('11') 11

If you give a string which is of inappropriate ‘value’ such as ‘hello’ which can’t be converted to a decimal integer, ValueError is raised.



Discussion

No Comment Found