3.1.19 異常處理
#多分支:被監測的代碼塊拋出的異常有多種可能性,並且我們需要針對每一種異常類型都定制專門的處理邏輯
# try:
# print(‘===>1‘)
# # name
# print(‘===>2‘)
# l=[1,2,3]
# # l[100]
# print(‘===>3‘)
# d={}
# d[‘name‘]
# print(‘===>4‘)
#
# except NameError as e:
# print(‘--->‘,e)
#
# except IndexError as e:
# print(‘--->‘,e)
#
# except KeyError as e:
# print(‘--->‘,e)
#
#
# print(‘====>afer code‘)
#萬能異常:Exception,被監測的代碼塊拋出的異常有多種可能性,
# 並且我們針對所有的異常類型都只用一種處理邏輯就可以了,那就使用Exception
# try:
# print(‘===>1‘)
# # name
# print(‘===>2‘)
# l=[1,2,3]
# l[100]
# print(‘===>3‘)
# d={}
# d[‘name‘]
# print(‘===>4‘)
#
# except Exception as e:
# print(‘異常發生啦:‘,e)
#
# print(‘====>afer code‘)
# try:
# print(‘===>1‘)
# # name
# print(‘===>2‘)
# l=[1,2,3]
# # l[100]
# print(‘===>3‘)
# d={}
# d[‘name‘]
# print(‘===>4‘)
#
# except NameError as e:
# print(‘--->‘,e)
#
# except IndexError as e:
# print(‘--->‘,e)
#
# except KeyError as e:
# print(‘--->‘,e)
#
# except Exception as e:
# print(‘統一的處理方法‘)
#
#
# print(‘====>afer code‘)
#其他結構
# try:
# print(‘===>1‘)
# # name
# print(‘===>2‘)
# l=[1,2,3]
# # l[100]
# print(‘===>3‘)
# d={}
# d[‘name‘]
# print(‘===>4‘)
#
# except NameError as e:
# print(‘--->‘,e)
#
# except IndexError as e:
# print(‘--->‘,e)
#
# except KeyError as e:
# print(‘--->‘,e)
#
# except Exception as e:
# print(‘統一的處理方法‘)
#
# else:
# print(‘在被檢測的代碼塊沒有發生異常時執行‘)
#
# finally:
# print(‘不管被檢測的代碼塊有無發生異常都會執行‘)
#
#
#
# print(‘====>afer code‘)
# try:
# f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))
#
# print(next(f))
# print(next(f))
# finally:
# f.close()
#主動觸發異常:raise 異常類型(值)
# class People:
# def __init__(self,name,age):
# if not isinstance(name,str):
# raise TypeError(‘名字必須傳入str類型‘)
# if not isinstance(age,int):
# raise TypeError(‘年齡必須傳入int類型‘)
#
# self.name=name
# self.age=age
#
# p=People(‘egon‘,18)
#自定義異常類型
class MyException(BaseException):
def __init__(self,msg):
super(MyException,self).__init__()
self.msg=msg
def __str__(self):
return ‘<%s>‘ %self.msg
raise MyException(‘我自己的異常類型‘) #print(obj)
#斷言assert
# info={}
# info[‘name‘]=‘egon‘
# # info[‘age‘]=18
#
#
#
#
#
#
# # if ‘name‘ not in info:
# # raise KeyError(‘必須有name這個key‘)
# #
# # if ‘age‘ not in info:
# # raise KeyError(‘必須有age這個key‘)
#
# assert (‘name‘ in info) and (‘age‘ in info)
#
#
#
# if info[‘name‘] == ‘egon‘ and info[‘age‘] > 10:
# print(‘welcome‘)
try:
pass
except Exception:
pass
3.1.19 異常處理