0

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?

3
  • You should really read the beginners docs on python.org! Commented Jan 13, 2009 at 9:40
  • 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. Commented Jan 13, 2009 at 9:41
  • -1: no failing code and no error traceback, I vote for closing the question as "not a real question". Commented Jan 13, 2009 at 11:34

6 Answers 6

5
try: 
    test()
except TypeError:
    print "error"
Sign up to request clarification or add additional context in comments.

Comments

1
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!

1 Comment

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

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"

Comments

1

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.

Comments

1

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)

Comments

0

This is valid:

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


test()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.