异常处理过程中,finally
可以指定必须执行的操作。
例如:
def divide(x,y):
try:
result = x/y
except ZeroDivisionError:
print('division by zero!')
else:
print(f'result is {result}')
finally:
print('executing finally clause')
执行:
In[3]: divide(2,1)
result is 2.0
executing finally clause
In[4]: divide(2,0)
division by zero!
executing finally clause
In[5]: divide("2","1")
executing finally clause
Traceback (most recent call last):
File "C:\Users\Administrator\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2910, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-5-c4579e894624>", line 1, in <module>
divide("2","1")
File "<ipython-input-2-6251857742e7>", line 3, in divide
result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
网友评论