alok kumar
alok kumar

Reputation: 67

Why doesn't exception handling work if I give only one argument to this function?

Here is a function:

def add(a, b):
try:
  return a + b
except TypeError:
  print('Error: It takes exactly 2 arguments')

This runs perfectly:

print(add(5,2))

This does not print the message I expect:

print(add(5))

Why?

Upvotes: 1

Views: 52

Answers (1)

schesis
schesis

Reputation: 59148

Your message doesn't get printed because the function is never called.

Here's a simpler example which doesn't try to catch any exceptions, to show what's going on:

# add_test.py

def add(a, b):
    return a + b

If you save this as a module add_test.py and then import it from an interactive Python session, you can try a couple of things out:

>>> from add_test import add
>>> add(5, 2)
7

This works as expected.

>>> add(5, 'x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/z/add_test.py", line 4, in add
    return a + b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

This raises TypeError inside the add() function (on line 4, as the traceback above tells you), because you can't add the integer 5 and the string 'x' together.

If you wanted to, you could catch this exception and print some kind of message:

# add_test_2.py

def add_exc(a, b):
    try:
        return a + b
    except TypeError:
        print("cannot add %r and %r." % (a, b))

… and it would behave as expected:

>>> from add_test_2 import add_exc
>>> add_exc(5, 'x')
cannot add 5 and 'x'.

However, when you miss out an argument completely, something different happens:

>>> add(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'b'

This raises TypeError immediately, without even trying to execute the code in add(), because when you defined add() you specified that it takes exactly two arguments: a and b. Your function is saying "I can only be called with two arguments", so Python follows that rule.

Since you haven't given Python a value for b in the second example, the function simply wouldn't make any sense if it were called, and Python knows that, so it refuses to try to do something that doesn't make any sense.

One way of looking at this is that you're getting two different kinds of TypeError in the two examples above:

  • When you call add(5, 'x') the problem is that 5 and 'x' are types of things that can't be added together, and you get a TypeError at the exact moment you break that rule.

  • When you try to call add(5), the problem is that add() is a type of function that must be called with two arguments, and you get a TypeError at the exact moment when you break that rule, which is before the function can even start.

Upvotes: 2

Related Questions