给定mylist = [0, 1]
def catch_index_error(value):
try:
return value
except IndexError:
return None
catch_index_error(mylist[5])
Run Code Online (Sandbox Code Playgroud)
返回一个IndexError
参数在函数执行之前计算,因此函数无法捕获异常。有办法捕捉吗?
该表达式mylist[5]会导致IndexError, 因为它是在调用函数之前计算的。
解决此问题的唯一方法是让函数从 中mylist返回正确的值:
mylist = [0,1]
def catch_index_error(index):
try:
return mylist[index]
except IndexError:
return None
catch_index_error(0) # returns '0'
catch_index_error(4) # returns None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10715 次 |
| 最近记录: |