检查以下有关python中异常处理的代码
class myException(Exception):
def __str__(self):
return 'this is my exception'
class myException2(Exception):
def __str__(self):
return 'this is my exception 2'
def myfunc():
try:
raise myException2
print('after exception')
except myException:
a = 'exception occur'
print(a)
else:
a = 'exception doesn\'t occur'
print(a)
finally:
a = 'no matter exception occurs or not'
print(a)
return a
Run Code Online (Sandbox Code Playgroud)
然后运行myfunc()将输出而不会弹出任何异常
no matter exception occurs or not
Run Code Online (Sandbox Code Playgroud)
但是如果注释中的finally子句中的'return a'代码,输出将捕获未处理的myException2,
no matter exception occurs or not
---------------------------------------------------------------------------
myException2 Traceback (most recent call last)
<ipython-input-140-29dfc9311b33> in <module>()
----> 1 myfunc()
<ipython-input-139-ba35768198b8> in myfunc()
1 def myfunc():
2 try:
----> 3 raise myException2
4 print('after exception')
5 except myException:
myException2: this is my exception 2
Run Code Online (Sandbox Code Playgroud)
为什么返回代码对捕获异常如此重要?
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |