Python之異常處理-Exception,python-exception

來源:互聯網
上載者:User

Python之異常處理-Exception,python-exception

在寫python程式時, 不要害怕報錯, 也不要怕自己的英語不夠好, 不要看到一有紅色的字就心裡發慫. 其實報的錯也是有套路可尋滴~識別了異常的種類, 才能對症下藥.

常見異常:

Exception                        所有異常的基類

AttributeError                 特性應用或賦值失敗時引發

IOError                             試圖開啟不存在的檔案時引發

IndexError                       在使用序列中不存在的索引時引發

KeyError                          在使用映射不存在的鍵時引發

NameError                       在找不到名字(變數)時引發

SyntaxError                     在代碼為錯誤形式時引發

TypeError                         在內建操作或者函數應用於錯誤類型的對象是引發

ValueError                       在內建操作或者函數應用於正確類型的對象,但是該對象使用不合適的值時引發

ZeroDivisionError          在除法或者摸除操作的第二個參數為0時引發

 

1. 拋出異常

def div(x,y):    if y == 0:        raise ZeroDivisionError('Zero is not allowed.')    return x/ytry:    div(4,0)except Exception as e:    print(e)
Zero is not allowed.Process finished with exit code 0

 

2. 捕捉異常:
可同時捕捉多個異常,可捕捉異常對象,可忽略異常類型以捕捉所有異常

try:      x = int(input('input x:'))      y = int(input('input y:'))      print('x/y = ',x/y)  except ZeroDivisionError: #捕捉除0異常      print("ZeroDivision")  except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出      print(e)  except: #捕捉其餘類型異常      print("it's still wrong")  
input x:3input y:0ZeroDivisionProcess finished with exit code 0
input x:5input y:ainvalid literal for int() with base 10: 'a'Process finished with exit code 0

try/except 可以加上 else 語句,實現在沒有異常時執行什麼

try:    x = int(input('input x:'))    y = int(input('input y:'))    print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0異常    print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出    print(e)except: #捕捉其餘類型異常    print("it's still wrong")else: #沒有異常時執行    print('it works well') 
input x:4input y:2x/y =  2.0it works wellProcess finished with exit code 0

3. finally 語句
不管是否出現異常,最後都會執行finally的語句塊內容,用於清理工作
所以,你可以在 finally 語句中關閉檔案,這樣就確保了檔案能正常關閉

try:    x = int(input('input x:'))    y = int(input('input y:'))    print('x/y = ',x/y)except ZeroDivisionError: #捕捉除0異常    print("ZeroDivision")except (TypeError,ValueError) as e: #捕捉多個異常,並將異常對象輸出    print(e)except: #捕捉其餘類型異常    print("it's still wrong")else: #沒有異常時執行    print('it works well')finally: #不管是否有異常都會執行    print("Cleaning up")
input x:4input y:ainvalid literal for int() with base 10: 'a'Cleaning upProcess finished with exit code 0

異常拋出之後,如果沒有被接收,那麼程式會拋給它的上一層,比如函數調用的地方,要是還是沒有接收,那繼續拋出,如果程式最後都沒有處理這個異常,那它就丟給作業系統了 -- 你的程式崩潰了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.