案列1
iterable = iter([1,2])
def func(iterable):
while True:
try:
print("ok")
print(next(iterable))
print("not ok")
except StopIteration:
print("I have already try try")
break
return "ok and not ok"
func(iterable)
运行结果:
ok
1
not ok
ok
2
not ok
ok
I have already try try
案列2
iterable = iter([1,2])
def func(iterable):
while True:
try:
print("ok")
yield next(iterable)
print("not ok")
except StopIteration:
print("I have already try try")
break
return "ok and not ok"
g = func(iterable)
print(next(g))
print(next(g))
print(next(g))
运行结果:
Traceback (most recent call last):
ok
1
not ok
ok
2
not ok
ok
I have already try try
File "D:/PycharmProjects/untitled1/5moth/512/exec.py", line 17, in
print(next(g))
StopIteration: ok and not ok
总结
异常有可能会出现不同的地方,有可能在方法之内出现异常,若在函数体内出现异常,通过捕获处理。
在代码分析过程中一定要判断一共有哪几个点会出现异常,一共会出现多少次异常,捕获了几次异常,如果已经捕获异常了,但是仍然又有异常,说明捕获的异常次数依然不够