python自動化學習8 異常處理

2021-09-03 10:52:10 字數 2691 閱讀 2635

異常:程式執行過程中出現的錯誤,都可以稱為異常

#異常的資訊包含:出錯的檔案、行數、具體的**、錯誤型別、錯誤資訊

異常處理:當程式執行,出現 異常的時候,對異常進行處理

try:

監控的**塊

except:

如果監控的**出現問題,該怎麼處理

例子1:

try:

file = open("test.txt","w",encoding = "utf-8")

print("讀操作之前")

res= file.read() #讀操作-----異常出現這裡。因為w為只寫     程式中斷

print("讀操作之後")

print('讀操作獲取的結果:'.format(res))

except:

file.write("讀操作報錯啦 ")

print('讀操作報錯啦')

#錯誤型別:baseexceptin     exception

#定位你的異常:明確你的錯誤型別 方便定位問題

try:

file = open("test.txt","w",encoding = "utf-8")

print("讀操作之前")

res= file.read() #讀操作-----異常出現這裡。因為w為只寫     程式中斷

print("讀操作之後")

print('讀操作獲取的結果:'.format(res))

except   baseexception as e:

file.write("讀操作報錯啦: ".format(e))#把錯誤資訊寫進file裡面去

print('讀操作報錯啦')

l=[1,2,3]

try:

print("獲取列表資料",l[4])

file = open("test.txt","w",encoding = "utf-8")

print("讀操作之前")

res= file.read() #讀操作-----異常出現這裡。因為w為只寫     程式中斷

print("讀操作之後")

print('讀操作獲取的結果:'.format(res))

except   ioerror as e:

file.write("讀操作報錯啦: ".format(e))#把錯誤資訊寫進file裡面去

print('讀操作報錯啦')

except   indexerror as e:

print('列表資料讀取報錯啦')

file.write("列表資料讀取報錯啦: ".format(e))#把錯誤資訊寫進file裡面去

##**的執行順序是從上到下,什麼地方會中斷,就會跑到except裡面去

##乙個異常可以包含多個except,但是乙個異常不能包含多個try

例子:l=[1,2,3]

try:

file = open("test.txt","w",encoding = "utf-8")

try:

print("獲取列表資料",l[4])

except  indexerror as e:

print('獲取列表錯誤:'.format(e))

file.write("獲取列表操作報錯了:".format(e))  ##處理完錯誤資訊,不會中斷,繼續往下執行

print("讀操作之前")

res= file.read() #讀操作-----異常出現這裡。因為w為只寫     程式中斷

print("讀操作之後")

print('讀操作獲取的結果:'.format(res))

except   ioerror as e:

file.write("讀操作報錯啦: ".format(e))#把錯誤資訊寫進file裡面去

print('讀操作報錯啦')  ###最後的結果:會抓到兩個異常資訊

try:

file = open("test.txt","w",encoding = "utf-8")

print("讀操作之前")

res= file.read() #讀操作-----異常出現這裡。因為w為只寫     程式中斷

print("讀操作之後")

print('讀操作獲取的結果:'.format(res))

except:

file.write("讀操作報錯啦 ")

print('讀操作報錯啦')

finally:

print("我執行的是finally語句!!!")

try:

file = open("test.txt","w+",encoding = "utf-8")

res= file.read() #讀操作

print('讀操作獲取的結果:'.format(res))  ##執行通過,無異常

except:

file.write("讀操作報錯啦 ")

print('讀操作報錯啦')

else:

try...except....else:只有在try裡面通過了才會執行else的語句

try...except....finally :finally的語句一定會執行

with open('test.txt','w')as file:

result = file.read()

print(result)

###作用是開啟了檔案後,之後會自動關閉

Python自動化學習 元素定位

from selenium import webdriver import time driver webdriver.chrome driver.get 元素定位之 id 定位 driver.find element by id kw send keys 華為 driver.find elemen...

python自動化學習筆記之pytest

特點 1,風格比較自由,可單獨定義方法,也可將方法封裝到class裡 2,引數化執行,可靈活配置測試計畫 3,可生成xml報告,方便結果分析及jenkins整合 安裝可以直接pip install pytest 檔名定義 test py or test.py 類定義 test開頭 方法定義 test...

python介面自動化學習之路(4)

1.迴圈讀取excel裡的case 2.將響應結果寫入乙個新的excel 需要引入xlwt import requests import xlrd import json import xlutils import xlwt import time excelfile r users documen...