成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

Python try-except-else-finally的具體使用

瀏覽:3日期:2022-08-07 08:01:55
目錄try-excepttry-except-elsetry-finallytry-except

作用:處理異常情況

用法:try:后面寫正常運(yùn)行的代碼,except + 異常情況:后面寫對(duì)異常情況的處理

示例:

try: num = int(input('Please input a number:n')) print(42 / num)except ZeroDivisionError: #except后為錯(cuò)誤類型 print('Divided by zero!')except ValueError: #可以有多個(gè)錯(cuò)誤類型 print('Wrong value!')

運(yùn)行結(jié)果:

Python try-except-else-finally的具體使用

Python try-except-else-finally的具體使用

Python try-except-else-finally的具體使用

注意:調(diào)用try語句時(shí),try后的所有錯(cuò)誤都將被捕捉,一旦遇到錯(cuò)誤,立即跳到except語句塊,錯(cuò)誤之后的語句不再執(zhí)行

def division(DivideBy):return 42 / DivideBytry: print(division(1)) print(division(0)) print(division(7))except ZeroDivisionError:#except后寫錯(cuò)誤類型print('Divided by zero!')

運(yùn)行結(jié)果:

Python try-except-else-finally的具體使用

try-except-else

和try-except類似,不過如果程序沒有錯(cuò)誤,也就是沒有跳到except語句塊,則執(zhí)行else語句塊,如果程序發(fā)生錯(cuò)誤,即跳到except語句塊,則直接跳過else語句塊

示例程序:

def division(DivideBy):return 42 / DivideBytry: num = int(input('Please input a integer:n')) print(division(num))except ZeroDivisionError:#except后寫錯(cuò)誤類型print('Divided by zero!')except ValueError: print('Wrong input!')else: print('No error. Good job!')

運(yùn)行結(jié)果:

Python try-except-else-finally的具體使用

Python try-except-else-finally的具體使用

Python try-except-else-finally的具體使用

try-finally

finally:無論try后是否有異常,都要執(zhí)行

def division(DivideBy): return 42 / DivideBytry: num = int(input('Please input a integer:n')) print(division(num))except ZeroDivisionError: # except后寫錯(cuò)誤類型 print('Divided by zero!')except ValueError: print('Wrong input!')else: print('No error. Good job!')finally: print('Finished')

運(yùn)行結(jié)果:

Python try-except-else-finally的具體使用

Python try-except-else-finally的具體使用

到此這篇關(guān)于Python try-except-else-finally的具體使用的文章就介紹到這了,更多相關(guān)Python try-except-else-finally 內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章: