Python學習筆記(10):異常

來源:互聯網
上載者:User

當程式執行的時候,可能會出現一些異常現象,這個可能是會存在的。例如,你在讀檔案的時候,而那個檔案不存在。此時,我們可以用異常來處理。

1. 錯誤

我們來做個簡單的測試,我們故意把print方法寫出Print。

>>> Print("Hello world")
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    Print("Hello world")
NameError: name 'Print' is not defined
>>>

系統會拋出NameError異常。

2. try..except

我們可以用try..except處理異常。

try:    f = open("test.txt")    f.close()except(IOError):    print("The file is not exist.")except:    print("Some error occurred.")print("Done")

運行結果:

The file is not exist.
Done

3. 引發異常

你可以用raise語句來引發異常。我們先自訂一個ShortInputError異常,需要繼承Exception類。

class ShortInputError(Exception):    '''A user-defined exception class.'''    def __init__(self, length, atleast):        Exception.__init__(self)        self.length = length        self.atleast = atleasttry:    s = input("Enter something -->")    if len(s) < 3:        raise(ShortInputError(len(s), 3))    #Other work can continue as usual hereexcept(EOFError):    print("Why did you do an EOF on me?")except ShortInputError as e:    print("ShortInputError: The input was of length %d, \was expecting at least %d" % (e.length, e.atleast))else:    print("No exception was raised.")

輸入兩個字元運行結果:

>>>
Enter something -->tr
ShortInputError: The input was of length 2, was expecting at least 3
>>>

輸入三個字元以上運行結果:

>>>
Enter something -->test
No exception was raised.
>>>

4. try..finally

假如你在讀一個檔案的時候,希望在無論異常發生與否的情況下都關閉檔案,該怎麼做呢?這可以使用finally塊來完成。注意,在一個try塊下,你可以同時使用except從句和finally塊。如果你要同時使用它們的話,需要把一個嵌入另外一個。

import timetry:    f = open("poem.txt")    while True: # our usual file-reading idiom        line = f.readline()        if len(line) == 0:            break        time.sleep(2)        print(line),finally:    f.close()    print("Cleaning up...closed the file")

運行結果:

>>>
Programming is fun

When the work is done

if you wanna make your work also fun:

    use Python!

Cleaning up...closed the file
>>>

def divide(x, y):    try:        result = x/ y    except ZeroDivisionError:        print("Division by zero!")    else:        print("result is", result)    finally:        print("executing finally clause")

測試結果:

>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
Division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    divide("2", "1")
  File "<pyshell#10>", line 3, in divide
    result = x/ y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
>>>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.