9 python 異常類的例項和清除異常

2021-10-01 04:14:26 字數 1050 閱讀 4246

看下面的例子

try:

x = [1,2,3]

print(x[4])

except indexerror as i:

print(i)

print(i.args)

執行結果

list index out of range

('list index out of range',)

再看乙個例子

try:

file = open("a","r")

except filenotfounderror as f:

print(f)

print(f.args)

執行結果

[errno 2] no such file or directory: 'a'

(2, 'no such file or directory')

看乙個例子

# 當程式資料正常會執行finally下面的語句

try:

x = [1,2,3]

print(x[2])

except indexerror as i:

print(i.args)

finally:

print("異常已經被清除")

執行結果

3

異常已經被清除

再看乙個例子

# 當程式資料不正常會執行finally下面的語句

try:

x = [1,2,3]

print(x[4])

except indexerror as i:

print(i.args)

finally:

print("異常已經被清除")

執行結果

('list index out of range',)

異常已經被清除

9 Python中的類(二)

子類繼承父類的屬性和方法,但不能繼承父類的私有屬性和私有方法 屬性名或方法名字首為兩個下劃線 類的繼承示例 class myclass class name myclass def init self,x 10,y 20,name myclass self.x x self.y y myclass....

Python筆記9 Python中的json

不了解json的可以先取看看json python中有自帶的json編碼器和解碼器 dumps loads dump load 以上四種方法是python中json的主要處理方法 定義兩個序列 l1 1,2,3,123 l2 dumps轉換 newl1 json.dumps l1 newl2 jso...

例項化servlet類異常 python類和例項化

從開始學習python我們就知道它是一門物件導向的語言,先來簡單的了解下物件導向的一些基本特徵。物件導向最重要的概念就是類 class 和例項 instance 類和模組差不多,我們通過模組可以儲存一些 並通過 運算子訪問這些 類說 俺也一樣!class後面接著是類名 中間有空格 即mypy,類名通...