Python之異常處理

2021-08-27 09:00:26 字數 3785 閱讀 8632

在程式執行過程中影響程式正常執行的內容,稱為異常

# # nameerror

# print(a)

# # indexerror: 索引錯誤

# li = [1,2,3,4]

# print(li[8])

# # keyerror

# d = dict(a=1, b=2)

# print(d['f'])

# # zerodivisionerror: 除0錯誤

# print(10/(2-2))

# class student(object):

# def __init__(self, name, age):

# self.name = name

# self.age = age

# def echo(self):

# print(self.name, self.age)

## # attributeerror: 物件沒有該屬性

# s1 = student("westos", 10)

# # print(s1.scores)

# # s1.echo()

# # s1.echo1()

# # filenotfounderror

# with open('/tmp/passwd9') as f:

# print(f.read(5))

# try:

# print(a)

# # 如果出現nameerror時, 不報錯, 只顯示except語句裡面執行的內容.

# except nameerror:

# print("name error")

# print("hello")

# print("hello1 ")

# 捕獲異常

try:

f = open("hello.txt", 'w')

f.write("這是乙個測試檔案")

# 注意: except語句不一定會執行, 只有在try語句中出現ioerror報錯時, 才會執行.

except ioerror as e:

print(e)

# print("沒有找到檔案或者檔案讀取失敗")

# 如果沒有捕獲到異常, 則執行else語句的內容

else:

print("檔案內容寫入成功")

# 無論是否捕獲到異常, 都執行的語句.

finally:

f.close()

print("檔案已經關閉")

## f = open("hello.txt", 'w')

# f.write("這是乙個測試檔案")

# f.write("這是乙個測試檔案")

f.read()

# 不建議捕獲所有的異常, 因為不能定位錯誤的位置.

except:

print("捕獲所有的異常....")

else:

print("如果沒有捕獲到異常, 執行else語句")

finally:

f.close()

print("有異常或者沒有異常都會執行")

print("沒有產生異常")

finally:

print("無論是否產生異常的清理操作")

# ************自定義異常類********************

# 所有的異常實際上是乙個類, 所以異常的父類都是baseexception.

# ioerror, indexerror, keyerror, fileexistserror

class

ageerror

(baseexception):

pass

defget_age

(age):if0

< age <= 200:

print(age)

else:

# 如果raise丟擲異常, 程式後面的**不會再執行.

# 丟擲異常

# 如果希望程式中的所有assert語句不執行, 那麼給python -o 指令碼名

python之異常處理 Python之異常處理

異常物件 請大家執行如下 a 100 0 print a 就會發現直譯器顯示如下的錯誤提示 traceback most recent call last file x.py line 1,in a 100 0 zerodivisionerror division by zero 大家要學會看直譯器...

Python之異常處理

try ret int input num 正常執行的 print ret except valueerror 捕捉錯誤 print 請輸入數字 try ret int input num 正常執行的 print ret except valueerror 捕捉錯誤 print 請輸入數字 exce...

Python之異常處理

異常處理結構 一.try except errortype as e 二.try except errortype as e finally 無論是否異常均會執行 三.try except exception 萬能異常捕獲 四.try 多分支結構 except errortype1 as e exc...