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?
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?
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!
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"
This is valid:
try:
def test():
print 'hi'
except:
print 'error'
test()
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.
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)