python raise語句 Python第三天

2021-10-11 19:38:57 字數 3305 閱讀 8920

一、學習內容概括

異常處理

二、具體學習內容

異常處理

異常就是執行期檢測到的錯誤。計算機語言針對可能出現的錯誤定義了異常型別,某種錯誤引發了對應的異常時,異常處理程式將被啟動,從而恢復程式的正常執行。

python標準異常總結

異常體系內部有層次關係,python異常體系中部分關係如下:

python標準警告總結

捕捉異常用try - except 語句

try:

檢測範圍exceptexception[asreason]:

出現異常後的處理**

try:

f = open('test.txt')

print(f.read())

f.close()

except oserror as error:

print('開啟檔案出錯n原因是:' + str(error))

# 開啟檔案出錯

# 原因是:[errno 2] no such file or directory: 'test.txt'

try:

int("abc")

s = 1 + '1'

f = open('test.txt')

print(f.read())

f.close()

except oserror as error:

print('開啟檔案出錯n原因是:' + str(error))

except typeerror as error:

print('型別出錯n原因是:' + str(error))

except valueerror as error:

print('數值出錯n原因是:' + str(error))

# 數值出錯

# 原因是:invalid literal for int() with base 10: 'abc'

dict1 = 

try:

x = dict1['y']

except lookuperror:

print('查詢錯誤')

except keyerror:

print('鍵錯誤')

else:

print(x)

# 查詢錯誤

dict1 = 

try:

x = dict1['y']

except keyerror:

print('鍵錯誤')

except lookuperror:

print('查詢錯誤')

else:

print(x)

# 鍵錯誤

try:

s = 1 + '1'

int("abc")

f = open('test.txt')

print(f.read())

f.close()

except (oserror, typeerror, valueerror) as error:

print('出錯了!n原因是:' + str(error))

# 出錯了!

# 原因是:unsupported operand type(s) for +: 'int' and 'str'

try - except - finally語句

try:

檢測範圍exceptexception[asreason]:

出現異常後的處理**finally:

無論如何都會被執行的**

def divide(x, y):

try:

result = x / y

print("result is", result)

except zerodivisionerror:

print("division by zero!")

finally:

print("executing finally clause")

divide(2, 1)

# result is 2.0

# executing finally clause

divide(2, 0)

# division by zero!

# executing finally clause

divide("2", "1")

# executing finally clause

# typeerror: unsupported operand type(s) for /: 'str' and 'str'

try - except - else語句

try:

檢測範圍except:

出現異常後的處理**else:

如果沒有異常執行這塊**

try:

fh = open("testfile.txt", "w")

fh.write("這是乙個測試檔案,用於測試異常!!")

except ioerror:

print("error: 沒有找到檔案或讀取檔案失敗")

else:

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

fh.close()

# 內容寫入檔案成功

觸發異常--raise語句

raise [exception [, args [, traceback]]]
try:

raise nameerror('hithere')

except nameerror:

print('an exception flew by!')

# an exception flew by!

py 拷貝目錄

將乙個資料夾中到所有目錄或者檔案都拷貝到另外乙個資料夾中 coding utf 8 utility.py import os author lee defcopyfolder sourcedir,targetdir for f in os.listdir sourcedir sourcefile o...

網路程式設計 py

學習目標 如何基於socket程式設計,來開發一款c s架構 c client客戶端 s server服務端 軟體 網路程式設計 實現計算機與計算機間的通訊 通訊協議 tcp 可靠,有狀態的,長連線的協議,像打 一樣 udp 不可靠,無連線,像發簡訊一樣 tcp和udp屬於運輸層 建立tcp sco...

py 語法改正

message hello,full name.title print message 注意 兩對引號的範圍 一對引號括hello 一對引號括感嘆號 切忌不要瞎矇。加號連線的是字串,所以左右兩邊都需要是字串性質的。列表 print 列表名 列印輸出最原始的符號加資料 print 字元名 列印輸出資料...