02.29 Python 异常处理中的 esle

前言

们知道,在Python中,我们是用try--excetp--来做异常处理的,但Python 有别于其他语法的是在异常处理中还提供了else的处理场景,是的,你没看错,就是在条件判断if--else-- 中的else,那我们接下来就来看看在异常处理中else有什么作用。

else 作用场景


<code>>>> def div():...     try:...             x = int(input('firsut num:'))...             y = int(input('second num:'))...             print(x/y)...     except:...             print('error')...     else:...             print('it is ok')...>>> div()firsut num:2second num:12.0it is ok/<code>

1.finally 与try联合使用 ,不管异常有没有触发,都会执行finally 语句块的内容。

<code>>>> def div():...     try:...             x = int(input('firsut num:'))...             y = int(input('second num:'))...             print(x/y)...     except:...             print('error')...     else:...             print('it is ok')...     finally:...             print('it is finally')...>>> div()firsut num:2second num:12.0it is okit is finally# 出现异常的情况>>> div()firsut num:1second num:0errorit is finally/<code>

从上面的例子可以看出,当没有捕获到异常时,else会执行,当捕获到异常时,else就不会执行,finally不管异常有没有触发,都会执行。


分享到:


相關文章: