[英]Python exception handling, detecting the function that caused the exception?
[英]Exception handling of a function in Python
假设我有一个函数定义:
def test():
print 'hi'
每当给出参数时,我都会收到TypeError。
现在,我要尝试使用def语句。 我该怎么做呢?
try:
test()
except TypeError:
print "error"
In [1]: def test():
...: print 'hi'
...:
In [2]: try:
...: test(1)
...: except:
...: print 'exception'
...:
exception
这是教程中的相关部分
顺便说说。 要解决此错误,请勿将函数调用包装在try-except中。 而是使用正确数量的参数来调用它!
你说
现在,我要尝试使用def语句。 这个怎么做。
def
语句是正确的,它没有引发任何异常。 因此, try
将无济于事。
引发异常的是对该函数的实际调用。 因此应改为try
:
try:
test()
except TypeError:
print "error"
如果您想在调用时抛出错误,听起来像是您想要的,可以尝试以下方法:
def test(*args):
if args:
raise
print 'hi'
这会将错误从调用位置转移到函数。 它通过*args
列表接受任意数量的参数。 不,我不知道您为什么要这样做。
在Python中处理可变数量的参数的更好方法如下:
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)
这是有效的:
try:
def test():
print 'hi'
except:
print 'error'
test()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.