每當(dāng)發(fā)生讓Python不知所措的錯(cuò)誤時(shí)愧沟,它都會(huì)創(chuàng)建一個(gè)異常對象,鲤遥。如果你編寫了處理該異常的代碼沐寺,程序?qū)⒗^ 續(xù)運(yùn)行;如果你未對異常進(jìn)行處理盖奈,程序?qū)⑼V够煳耄@示一個(gè)traceback,其中包含有關(guān)異常的報(bào)告
1.使用try-except代碼塊
try:
print(5/0)
except ZeroDivisionError:
print("you can't divide by zero")
2.使用異常避免崩潰
try-except-else 代碼塊
print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number=input('\nFirst number: ')
if first_number == 'q':
break
second_number = input('\nsecond_number: ')
try:#只有可能引發(fā)異常的代碼才需要放在try 語句中
answer = int(first_number)/int(second_number)
except ZeroDivisionError:#except 代碼塊告訴Python卜朗,如果它嘗試運(yùn)行try 代碼塊中的代碼時(shí)引發(fā)了指定的異常拔第,該怎么辦
print("You can't divide by zero")
else:#僅在try 代碼塊成功 執(zhí)行時(shí)才需要運(yùn)行的代碼應(yīng)放在else 代碼塊中
print(answer)
3.文件找不到的或者文件名不正確,這樣的情況也是使用try-except
filename='miss.txt'
try:
with open(filename) as m_obj:
contents = m_obj.read()
except FileNotFoundError:
msg="Sorry, the file " + filename + " does not exist."
print(msg)
4.想要失敗的時(shí)候“一聲不吭”
filename='miss.txt'
try:
with open(filename) as m_obj:
contents = m_obj.read()
except FileNotFoundError:
pass#出現(xiàn)FileNotFoundError 異常時(shí)场钉,將執(zhí)行except 代碼塊中的代碼蚊俺,但什么都不會(huì)發(fā)生逛万,不會(huì)出現(xiàn)traceback泳猬,也沒有任何輸出
else: