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


有一個 Exception 類,它是 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-02-12

425 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.