美文网首页Py100Skills
[Py004] 异常处理

[Py004] 异常处理

作者: 安哥生个信 | 来源:发表于2018-10-16 12:21 被阅读25次

异常处理过程中,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'

相关文章

网友评论

    本文标题:[Py004] 异常处理

    本文链接:https://www.haomeiwen.com/subject/edxhzftx.html