How to handle the error that occurs on giving wrong number of parameters in a function call in Python?

StackOverflow https://stackoverflow.com/questions/456673

  •  19-08-2019
  •  | 
  •  

Question

When i give wrong number of parameters in a function , i get errors. How do I handle it?

I gave

def fun_name(...):
    try:
        ...

    except TypeError:
        print 'Wrong no of arg'

It is not working.

Help please.

Was it helpful?

Solution

The caller triggers this exception, not the receiver.

If you want the receiving function to explicitly check argument count you'll need to use varargs:

def fun_name(*args):
  if len(args) != 2:
    raise TypeError('Two arguments required')

OTHER TIPS

You need to handle it where you call the function.

try:
  fun_name(...)
except TypeError:
  print "error!"

If you call a function with the wrong number of parameters then there are two possibilities:

  • Either you design your function to handle an arbitrary number of arguments. Then you should know what to do with the extra arguments. The answer of Alec Thomas shows you how to handle this case.
  • Or your design is fundamentally flawed and you are in deep trouble. Catching the error doesn't help in this case.

If you remove the try...catch parts it should show you what kind of exception it is throwing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top