<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    qileilove

    blog已經轉移至github,大家請訪問 http://qaseven.github.io/

    python異常

    python異常

     

    python用異常對象(exception object)來表示異常情況。遇到錯誤后,會引發異常。如果異常對象并未被處理或捕捉,程序就會用所謂的 回溯(Traceback, 一種錯誤信息)終止執行:

    >>> 1/0  Traceback (most recent call last):   File "<pyshell#0>", line 1, in <module>     1/0 ZeroDivisionError: integer division or modulo by zero

     

     

    raise 語句

    為了引發異常,可以使用一個類(Exception的子類)或者實例參數數調用raise 語句。下面的例子使用內建的Exception異常類:

    復制代碼
    >>> raise Exception    #引發一個沒有任何錯誤信息的普通異常  Traceback (most recent call last):   File "<pyshell#1>", line 1, in <module>     raise Exception Exception >>> raise Exception('hyperdrive overload')   # 添加了一些異常錯誤信息  Traceback (most recent call last):   File "<pyshell#2>", line 1, in <module>     raise Exception('hyperdrive overload') Exception: hyperdrive overload
    復制代碼

     

    系統自帶的內建異常類:

    復制代碼
    >>> import exceptions >>> dir(exceptions) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
    復制代碼

    哇!好多,常用的內建異常類:

     

     

    自定義異常

    盡管內建的異常類已經包括了大部分的情況,而且對于很多要求都已經足夠了,但有些時候還是需要創建自己的異常類。

    和常見其它類一樣----只是要確保從Exception類繼承,不管直接繼承還是間接繼承。像下面這樣:

    >>> class someCustomExcetion(Exception):pass

    當然,也可以為這個類添加一些方法。

     

     

    捕捉異常

    我們可以使用 try/except 來實現異常的捕捉處理。

    假設創建了一個讓用戶輸入兩個數,然后進行相除的程序:

    復制代碼
    x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y  #運行并且輸入 Enter the first number: 10 Enter the second number: 0  Traceback (most recent call last):   File "I:/Python27/yichang", line 3, in <module>     print x/y ZeroDivisionError: integer division or modulo by zero
    復制代碼

     

    為了捕捉異常并做出一些錯誤處理,可以這樣寫:

    復制代碼
    try:     x = input('Enter the first number: ')     y = input('Enter the second number: ')     print x/y except ZeroDivisionError:   print "輸入的數字不能為0!"    #再來云行 >>>  Enter the first number: 10 Enter the second number: 0 輸入的數字不能為0!           #怎么樣?這次已經友好的多了
    復制代碼

    假如,我們在調試的時候引發異常會好些,如果在與用戶的進行交互的過程中又是不希望用戶看到異常信息的。那如何開啟/關閉 “屏蔽”機制?

    復制代碼
    class MuffledCalulator:     muffled = False   #這里默認關閉屏蔽     def calc(self,expr):         try:             return eval(expr)         except ZeroDivisionError:             if self.muffled:                 print 'Divsion by zero is illagal'             else:                 raise  #運行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0')  Traceback (most recent call last):   File "<pyshell#30>", line 1, in <module>     calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac'   #異常信息被輸出了  >>> calculator.muffled = True   #現在打開屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal 
    復制代碼

     

     

    多個except 子句

    如果運行上面的(輸入兩個數,求除法)程序,輸入面的內容,就會產生另外一個異常:

    復制代碼
    try:     x = input('Enter the first number: ')     y = input('Enter the second number: ')     print x/y except ZeroDivisionError:   print "輸入的數字不能為0!"    #運行輸入: >>>  Enter the first number: 10 Enter the second number: 'hello.word'  #輸入非數字  Traceback (most recent call last):   File "I:\Python27\yichang", line 4, in <module>     print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str'  #又報出了別的異常信息
    復制代碼

     

    好吧!我們可以再加個異常的處理來處理這種情況:

    復制代碼
    try:     x = input('Enter the first number: ')     y = input('Enter the second number: ')     print x/y except ZeroDivisionError:     print "輸入的數字不能為0!" except TypeError:           # 對字符的異常處理   print "請輸入數字!"    #再來運行: >>>  Enter the first number: 10 Enter the second number: 'hello,word' 請輸入數字!
    復制代碼

     

     

    一個塊捕捉多個異常

    我們當然也可以用一個塊來捕捉多個異常:

    try:     x = input('Enter the first number: ')     y = input('Enter the second number: ')     print x/y except (ZeroDivisionError,TypeError,NameError):     print "你的數字不對!"

     

     

    捕捉全部異常

    就算程序處理了好幾種異常,比如上面的程序,運行之后,假如我輸入了下面的內容呢

    復制代碼
    >>>  Enter the first number: 10 Enter the second number:   #不輸入任何內容,回車  Traceback (most recent call last):   File "I:\Python27\yichang", line 3, in <module>     y = input('Enter the second number: ')   File "<string>", line 0         ^ SyntaxError: unexpected EOF while parsing
    復制代碼

     

    暈死~! 怎么辦呢?總有被我們不小心忽略處理的情況,如果真想用一段代碼捕捉所有異常,那么可在except子句中忽略所有的異常類:

    復制代碼
    try:     x = input('Enter the first number: ')     y = input('Enter the second number: ')     print x/y except:     print '有錯誤發生了!'  #再來輸入一些內容看看 >>>  Enter the first number: 'hello' * )0  有錯誤發生了!
    復制代碼

     

     

    結束

    別急!再來說說最后一個情況,好吧,用戶不小心輸入了錯誤的信息,能不能再給次機會輸入?我們可以加個循環,保你輸對時才結束:

    復制代碼
    while True:          try:         x = input('Enter the first number: ')         y = input('Enter the second number: ')         value = x/y         print 'x/y is',value
    break
    except: print '列效輸入,再來一次!' #運行 >>> Enter the first number: 10 Enter the second number: 列效輸入,再來一次! Enter the first number: 10 Enter the second number: 'hello' 列效輸入,再來一次! Enter the first number: 10 Enter the second number: 2 x/y is 5
    復制代碼

     

     ------------------------

    溫馨提示:因為是學習筆記,盡量精簡了文字,所以,你要跟著做才能體會,光看是沒用的(也沒意思)。

     

    posted on 2014-02-13 17:27 順其自然EVO 閱讀(201) 評論(0)  編輯  收藏 所屬分類: python

    <2025年5月>
    27282930123
    45678910
    11121314151617
    18192021222324
    25262728293031
    1234567

    導航

    統計

    常用鏈接

    留言簿(55)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 久久亚洲AV成人无码| 日本高清免费中文字幕不卡| 国产日产亚洲系列最新| 日韩精品亚洲专区在线影视| 成人免费毛片视频| 亚洲av乱码一区二区三区按摩 | 亚洲欧洲精品一区二区三区| 久久午夜无码免费| 亚洲综合日韩中文字幕v在线| 亚洲免费在线播放| 亚洲免费中文字幕| 浮力影院第一页小视频国产在线观看免费 | 亚洲国产精品日韩在线观看 | 亚洲AⅤ男人的天堂在线观看| 永久黄网站色视频免费直播| mm1313亚洲国产精品无码试看| 国产成人免费片在线视频观看| 老司机午夜性生免费福利| 亚洲成a人片在线观看老师| 国产男女爽爽爽免费视频| 国产aⅴ无码专区亚洲av| 亚洲免费视频网站| 亚洲日韩精品无码专区加勒比 | 色婷婷综合缴情综免费观看| 狠狠色婷婷狠狠狠亚洲综合| 女人体1963午夜免费视频| 亚洲在成人网在线看| 国产视频精品免费| 拍拍拍无挡视频免费观看1000| 在线电影你懂的亚洲| 免费毛片在线播放| 国产线视频精品免费观看视频| 91嫩草私人成人亚洲影院| 爽爽日本在线视频免费| 三年片在线观看免费西瓜视频| 亚洲人成电影在线观看网| 亚洲国产小视频精品久久久三级| 久久一本岛在免费线观看2020| 亚洲人成网站999久久久综合| 亚洲日韩VA无码中文字幕| 国产1000部成人免费视频|