如何在 Python 中捕獲 StandardError 異常?\\n


有異常類,它是 StopIteration、StandardError 和 Warning 的基類。所有標準錯誤都派生自 StandardError。一些標準錯誤,如 ArithmeticErrror、AttributeError、AssertionError 派生自基類 StandardError。

當屬性引用或賦值失敗時,將引發 AttributeError。例如,當嘗試引用不存在的屬性時

我們重寫給定的程式碼並捕獲異常並瞭解其型別。

示例

import sys
try:
class Foobar:
def __init__(self):
self.p = 0
f = Foobar()
print(f.p)
print(f.q)
except Exception as e:
print e
print sys.exc_type
print 'This is an example of StandardError exception'

輸出

0
Foobar instance has no attribute 'q'
<type 'exceptions.AttributeError'>
This is an example of StandardError exception

更新於: 2020 年 2 月 12 日

424 次瀏覽

開啟你的 職業生涯

完成此課程以取得認證

開始
廣告
© . All rights reserved.