1. 程式人生 > >面向物件 10 異常處理&try...except用法

面向物件 10 異常處理&try...except用法

什麼是異常處理:異常是錯誤發生的訊號,一旦程式出錯,並且程式沒有處理這個錯誤,那個就會丟擲異常,並i企鵝程式的允許隨之終止

print('1')
print('2')
print('3')
int('aaaaa')
print('4')
print('5')
print('6')

錯誤分兩種 1 語法錯誤 程式執行前就要立刻改正過來

print('xxx')
if 1>2

2邏輯錯誤

ValueError:
int(‘aaa')

NameError
name

TypeError


.........

3 異常 強調一:對於錯誤發生的條件是可以預知的,此時應該用if判斷去預防異常

AGE=10
age = input('>>:').strip()

if age.isdigit():
    age=int(age)
    age=int(age)
    if age >AGE:
       print("太大了")

強調二:如果錯誤發生的條件是不可預知的,此時應該用異常處理機制,try…except

try:
    f=open('a.txt','r',encoding='utf-8')
    print(next(f),end='')
    print(next(f),end='')
    print(next(f),end='')
    print(next(f),end='')
    print(next(f),end='')
    print(next(f),end='')
    f.close()
except StopIteration:
    print('出錯')

print('>>>>>>>>>11')
print('>>>>>>>>>>22')
print('>>>>>>>>>##3')

多分支:被監測的程式碼塊丟擲的異常有多種可能性,並且我們需要針對每一種異常型別都定製專門的處理邏輯


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)

萬能異常: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('========>after 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('========>after 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 Exception as e:
    print('統一處理方法')

else:
    print('在被檢測的程式碼塊沒有發生異常是執行')
finally:
    print('不管被檢測的程式碼塊有無發生異常都會執行')
print('========>after 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 isinstance(name,str):
            raise TypeError('名字必須轉入str型別')
        if not isinstance(age,str):
            raise TypeError('年齡必須傳入int型別')
        self.name=name
        self.age=age
p=People('efon',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')
# if info['name'] == 'egon' and info['age']>18:
#     print('welcome')

assert ('name' in info) and ('age' in info)