Exception

exceptions_handle.py

# 異常的處理
# try...except
# 通常的語句在try塊里  錯誤處理器放在except塊里


try:
    text = input('Enter something --> ')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('You entered {}'.format(text))
    
# 如果 except 后面不指定錯誤名稱 那么就是處理所有錯誤
# else 將在沒有發(fā)生異常的時候執(zhí)行

exceptions_raise.py

# 引發(fā)raise異常
# 要提供錯誤名或異常名以及要拋出Thrown的對象

class ShortInputException(Exception):
    '''一個由用戶定義的異常類'''
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text),3)
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print('ShortInputException: The input was ' + '{0} long, excepted at least {1}'.format(ex.length,ex.atleast))
else:
    print('No exception was raised.')

exceptions_finally.py

# try ... finally
# 主要是用在文件里面

import sys
import time

f = None
try:
    f = open('poem.txt')
    
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line,end='')
        # 以便print的內(nèi)容可以被立即打印到屏幕上
        sys.stdout.flush()
        print('Press ctrl+c now')
        
        # 每打印一行后插入兩秒休眠,讓程序運行得比較緩慢
        time.sleep(2)
except IOError:
    print('Could not find file poem.txt')
except KeyboardInterrupt:
    print('!! You cancelled the reading from the file.')
finally:
    if f:   # 這句話記得要
        f.close()
    print('(Clearning up:Closed the file)')

exceptions_using_with.py

# 在try塊中獲取資源(也就是open) 然后在finally塊中釋放資源(也就是close())
# with語句可以很簡單做到這一模式

with open('opem.txt') as f:
    for line in f:
        print(line,end='')

# 文件的關閉交由with ... open來完成
# with 會獲取open返回的對象f
# 然后在代碼塊開始之前調(diào)用 f.__enter__函數(shù) 
# 在代碼塊結(jié)束之后調(diào)用 f.__exit__函數(shù)
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Exception hierarchy? The class hierarchy for built-in exc...
    龐貝船長閱讀 3,400評論 1 0
  • RuntimeException# You never need to write an exception sp...
    華山野老閱讀 347評論 0 3
  • 異常是軟件系統(tǒng)不可避免的的問題,軟件系統(tǒng)在運行中難免發(fā)生不可預知的錯誤,為了避免異常造成軟件自動停止運行造成損失,...
    田文健閱讀 326評論 0 0
  • 更多 Java 基礎知識方面的文章,請參見文集《Java 基礎知識》 Java Exception Class D...
    專職跑龍?zhí)?/span>閱讀 509評論 0 1
  • 還要在窗口看多少次日落 眼中才會出現(xiàn)你的背影 玻璃上勇敢的雨滴 一次又一次的相遇 卻也只留下孤獨的痕跡 我養(yǎng)了花 ...
    說書客閱讀 266評論 0 0

友情鏈接更多精彩內(nèi)容