views:

124

answers:

4

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.

A: 

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

Harley
+4  A: 

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')
Alec Thomas
Thank you Alec.I m new to Python....so please answer this. If i want to use the value of args inside fun_name,say,to call another function, what should i do ?
@rejinacm: You should really read the tutorial. This would really help you understand Python better. Here argument lists are explained: http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists
unbeknown
+4  A: 

You need to handle it where you call the function.

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

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.
unbeknown