不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2020-09-19 22:46:01  修改时间:2024-04-30 14:01:17  分类:Python基础  编辑

一.try/except简介

  • try/except语句:主要是用于处理程序正常执行过程中出现的一些异常情况,如语法错误(python作为脚本语言没有编译的环节,在执行过程中对语法进行检测,出错后发出异常消息)、数据除零错误、从未定义的变量上取值等;
  • try/finally语句:则主要用于在无论是否发生异常情况,都需要执行一些清理工作的场合。即如果不想程序因为异常情况而中断,就可以用try来捕获,然后交予except来处理。

二.处理流程

try:
    code    #需要判断是否会抛出异常的代码,如果没有异常处理,python会直接停止执行程序
 
except:  #这里会捕捉到上面代码中的异常,并根据异常抛出异常处理信息
#except ExceptionName,args:    #同时也可以接受异常名称和参数,针对不同形式的异常做处理
 
    code  #这里执行异常处理的相关代码,打印输出等
 
else:  #如果没有异常则执行else
 
    code  #try部分被正常执行后执行的代码
 
finally:
    
    code  #退出try语句块总会执行的程序

可以看到:

1.这里的 else 是和 try except 连用的,并且 else 只在 try 中代码没有异常的情况下执行,else 必须在 except 这句代码存在的时候才能出现。

2.finally这个片段里面的代码是肯定在最后执行的,无论前面是否发生异常,最后总会执行finally片段内的代码。

所以,正常的流程是:try没有发生错误 =》else内的代码 =》finally中的代码。

发生异常的流程是:try中发生异常 =》被except捕获并执行except片段中的代码 =》执行finally中的代码。

三.案例展示

定义产生异常的函数。

def divide(a,b):
    return a/b

1.通过try-except捕获异常

try:
    divide(1, 0)
except:
    print("divide by 0")
else:
    print("the code is no problem")

print("code after try catch, hello world!")

输出:

divide by 0
code after try catch, hello world!

可以看到,try except 捕获异常后依然可以执行后面的代码,并且捕获到了异常执行异常中的代码。并且 else 在捕获到异常的时候并不执行。

2.else只在没有异常的时候执行

try:
    divide(1, 1)
except:
    print("divide by 0")
else:
    print("the code is no problem")

print("code after try catch, hello world!")

输出:

the code is no problem
code after try catch, hello world!

3.finally总在最后执行,不管有没有异常

try:
    divide(1, 1)
except:
    print("divide by 0")
else:
    print("the code is no problem")
finally:
    print("this is finally code,i'm running")

try:
    divide(1, 0)
except:
    print("divide by 0")
else:
    print("the code is no problem")
finally:
    print("this is finally code,i'm running")

输出:

the code is no problem
this is finally code,i'm running
divide by 0
this is finally code,i'm running

 

 

参考:https://blog.csdn.net/lwgkzl/article/details/81059433