如何在 Python 中捕獲 ZeroDivisionError 異常?


當除法操作的分母出現 0 時,將引發 ZeroDivisionError。

我們將給定的程式碼重寫如下以處理異常並查詢其型別。

示例

import sys
try:
x = 11/0
print x
except Exception as e:
print sys.exc_type
print e

輸出

<type 'exceptions.ZeroDivisionError'>
integer division or modulo by zero

更新時間: 12-2 月-2020

463 次瀏覽

開始您的 職業生涯

完成課程並獲得認證

開始
廣告