您好,登錄后才能下訂單哦!
異常就是程序運(yùn)行時(shí)發(fā)生的錯(cuò)誤,發(fā)生錯(cuò)誤時(shí)程序會(huì)終止執(zhí)行。
#語(yǔ)法錯(cuò)誤示范一
if
#語(yǔ)法錯(cuò)誤示范二
def test:
pass
#語(yǔ)法錯(cuò)誤示范三
class Foo
pass
#語(yǔ)法錯(cuò)誤示范四
print(haha)
#TypeError:int類型不可迭代
for i in 3:
pass
#ValueError
num=input(">>: ") #輸入hello
int(num)
#NameError
aaa
#IndexError
l=['egon','aa']
l[3]
#KeyError
dic={'name':'egon'}
dic['age']
#AttributeError
class Foo:pass
Foo.x
#ZeroDivisionError:無(wú)法完成計(jì)算
res1=1/0
res2=1+'str'
AttributeError 試圖訪問(wèn)一個(gè)對(duì)象沒(méi)有的樹形,比如foo.x,但是foo沒(méi)有屬性x
IOError 輸入/輸出異常;基本上是無(wú)法打開文件
ImportError 無(wú)法引入模塊或包;基本上是路徑問(wèn)題或名稱錯(cuò)誤
IndentationError 語(yǔ)法錯(cuò)誤(的子類) ;代碼沒(méi)有正確對(duì)齊
IndexError 下標(biāo)索引超出序列邊界,比如當(dāng)x只有三個(gè)元素,卻試圖訪問(wèn)x[5]
KeyError 試圖訪問(wèn)字典里不存在的鍵
KeyboardInterrupt Ctrl+C被按下
NameError 使用一個(gè)還未被賦予對(duì)象的變量
SyntaxError Python代碼非法,代碼不能編譯(個(gè)人認(rèn)為這是語(yǔ)法錯(cuò)誤,寫錯(cuò)了)
TypeError 傳入對(duì)象類型與要求的不符合
UnboundLocalError 試圖訪問(wèn)一個(gè)還未被設(shè)置的局部變量,基本上是由于另有一個(gè)同名的全局變量,
導(dǎo)致你以為正在訪問(wèn)它
ValueError 傳入一個(gè)調(diào)用者不期望的值,即使值的類型是正確的
如果錯(cuò)誤發(fā)生的條件是可預(yù)知的,我們需要用if進(jìn)行處理:在錯(cuò)誤發(fā)生之前進(jìn)行預(yù)防
AGE=10
while True:
age=input('>>: ').strip()
if age.isdigit(): #只有在age為字符串形式的整數(shù)時(shí),下列代碼才不會(huì)出錯(cuò),該條件是可預(yù)知的
age=int(age)
if age == AGE:
print('you got it')
break
如果錯(cuò)誤發(fā)生的條件是不可預(yù)知的,則需要用到try...except:在錯(cuò)誤發(fā)生之后進(jìn)行處理
#基本語(yǔ)法為
try:
被檢測(cè)的代碼塊
except 異常類型:
try中一旦檢測(cè)到異常,就執(zhí)行這個(gè)位置的邏輯
#舉例
try:
f=open('a.txt')
g=(line.strip() for line in f)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
except StopIteration:
f.close()
"1.異常類只能用來(lái)處理指定的異常情況,如果非指定異常則無(wú)法處理"
s1 = 'hello'
try:
int(s1)
except IndexError as e: # 未捕獲到異常,程序直接報(bào)錯(cuò)
print e
"2.多分支"
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
"3.萬(wàn)能異常Exception"
s1 = 'hello'
try:
int(s1)
except Exception as e:
print(e)
"4.也可以在多分支后來(lái)一個(gè)Exception"
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
except Exception as e:
print(e)
"5.異常的其他機(jī)構(gòu)"
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
#except Exception as e:
# print(e)
else:
print('try內(nèi)代碼塊沒(méi)有異常則執(zhí)行我')
finally:
print('無(wú)論異常與否,都會(huì)執(zhí)行該模塊,通常是進(jìn)行清理工作')
"6.主動(dòng)觸發(fā)異常"
try:
raise TypeError('類型錯(cuò)誤')
except Exception as e:
print(e)
"7.自定義異常"
class EgonException(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):
return self.msg
try:
raise EgonException('類型錯(cuò)誤')
except EgonException as e:
print(e)
"8.斷言:assert 條件"
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: vita
assert 1 == 1
assert 1 == 2
E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
Traceback (most recent call last):
File "E:/PythonProject/python-test/BasicGrammer/test.py", line 5, in <module>
assert 1 == 2
AssertionError
Process finished with exit code 1
9.總結(jié)try..except
1:把錯(cuò)誤處理和真正的工作分開來(lái)
2:代碼更易組織,更清晰,復(fù)雜的工作任務(wù)更容易實(shí)現(xiàn);
3:更安全了,不至于由于一些小的疏忽而使程序意外崩潰了;
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。