views:

350

answers:

6

Suppose I have a function definiton:

def test():
    print 'hi'

I get a TypeError whenever I gives an argument.

Now, I want to put the def statement in try. How do I do this?

+4  A: 
try: 
    test()
except TypeError:
    print "error"
hasen j
+1  A: 
In [1]: def test():
     ...:     print 'hi'
     ...:

In [2]: try:
     ...:     test(1)
     ...: except:
     ...:     print 'exception'
     ...:
exception

Here is the relevant section in the tutorial

By the way. to fix this error, you should not wrap the function call in a try-except. Instead call it with the right number of arguments!

unbeknown
At the first sentence itself its an error
Can you edit your question and show the exact code and error message you get. It's hard to see what your problem is and how to fix it.
unbeknown
+1  A: 

You said

Now, I want to put the def statement in try. How to do this.

The def statement is correct, it is not raising any exceptions. So putting it in a try won't do anything.

What raises the exception is the actual call to the function. So that should be put in the try instead:

try: 
    test()
except TypeError:
    print "error"
nosklo
A: 

This is valid:

try:
  def test():
    print 'hi'
except:
  print 'error'


test()
Harriv
+1  A: 

If you want to throw the error at call-time, which it sounds like you might want, you could try this aproach:

def test(*args):
    if args:
        raise
    print 'hi'

This will shift the error from the calling location to the function. It accepts any number of parameters via the *args list. Not that I know why you'd want to do that.

recursive
+1  A: 

A better way to handle a variable number of arguments in Python is as follows:

def foo(*args, **kwargs):
    # args will hold the positional arguments
    print args

    # kwargs will hold the named arguments
    print kwargs


# Now, all of these work
foo(1)
foo(1,2)
foo(1,2,third=3)
Triptych