当前位置:首页 » python教程 » 正文

Python try except异常捕获机制原理解析

看: 807次  时间:2020-07-17  分类 : python教程

当你执行大型程序的时候,突然出现exception,会让程序直接停止,这种对服务器自动程序很不友好,而python有着较好的异常捕获机制,不会立刻终止程序。

这个机制就是try-except。

1. 发生异常时可配置备用程序

aa = [1,2,4,5,7,0,2]
for ii in aa:
  try:
    h = 2/ii
    print(h)
  except:  #发生异常时备用
    h = 2/(ii+1)
    print(h)

2. 单个异常捕获

dict_ = {}
try:
  print(dict_['test'])
  print(' --- testing... --- ')
except KeyError as e:
  print('--- the error is ---:', e)  #单个异常
print(' ---finished!!--- ')

3. 多个异常捕获,循环中

num = [9,7,0,1,4,'16']
for x in num:
  try: 
    print (1/x)
  except ZeroDivisionError:
    print('error:0做除数!')
  except TypeError: # 当报错信息为TypeError,执行下面的语句。
    print('error:数值类型错误!')
print(' ---finished!!--- ')

4. 通用异常:Exception,当你不知道异常的种类或者多少异常的时候,可以使用通用异常捕获,同时通用异常可以与特定异常混用。

num = [9,7,0,1,4,'16']
for x in num:
  try: 
    print (1/x)
  except ZeroDivisionError:
    print('error:0做除数!')  #特定异常和Exception混合使用
  except Exception as e:
    print('the Exception is:',e)
print(' ---finished!!--- ')

5. else语句:在被检测的代码块没有发生异常时执行

dict_ = {'test':'这个地方是哪里?'}
try:
  print(dict_['test'])
  print(' --- testing... --- ')
except KeyError as e:
  print('--- the error is ---:', e)  #单个异常
else:
  print('没有发生异常!')
print(' ---finished!!--- ')

6. finally语句:不管有没有发生异常都会执行

dict_ = {'test':'这个地方是哪里?'}
try:
  print(dict_['test'])
  print(' --- testing... --- ')
except KeyError as e:
  print('--- the error is ---:', e)  #单个异常
else:
  print('没有发生异常!')
finally:
  print('总可以被执行的语句。。。')
print(' ---finished!!--- ')

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持python博客。

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!