python異常中else的實例用法
發(fā)布日期:2022-03-11 16:21 | 文章來源:gibhub
1、說明
當(dāng)確定沒有異常后,還需要做一些事情可以使用else語句。
注意:try中沒有異常,else之后的代碼才會被執(zhí)行。
2、實例
while True: try: x = int(input('請輸入X:')) y = int(input('請輸入Y:')) value = x / y print('x/y is',value) except Exception as e: # 發(fā)生異常時執(zhí)行 print('不正確的輸入:', e) print('請重新輸入') else: # 未發(fā)生異常時執(zhí)行 break
實例擴展:
def fetcher(obj, index): return obj[index] x = 'spam' try: print fetcher(x, 3) except Exception: print 'hhh' else: print 'has no exception' print fetcher(x, 2) print '---' * 10 try: print fetcher(x, 4) except IndexError: print 'got exception' else: print 'has no exception' print fetcher(x, 2)
運行結(jié)果:
m has no exception a ------------------------------ got exception
到此這篇關(guān)于python異常中else的實例用法的文章就介紹到這了,更多相關(guān)python異常中else的使用內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章