python異常中else的實例用法
當確定沒有異常后,還需要做一些事情可以使用else語句。
注意:try中沒有異常,else之后的代碼才會被執(zhí)行。
2、實例while True: try:x = int(input(’請輸入X:’))y = int(input(’請輸入Y:’))value = x / yprint(’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é)果:
mhas no exceptiona------------------------------got exception
到此這篇關(guān)于python異常中else的實例用法的文章就介紹到這了,更多相關(guān)python異常中else的使用內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. 如何清空python的變量3. Python 如何展開嵌套的序列4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. Spring security 自定義過濾器實現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實例代碼)6. Java類加載機制實現(xiàn)步驟解析7. Python TestSuite生成測試報告過程解析8. Python os庫常用操作代碼匯總9. Python OpenCV去除字母后面的雜線操作10. 增大python字體的方法步驟
