python应用_异常处理

我们把可能发生错误的语句放在try模块里,用except来处理异常。

参考学习链接:

https://www.cnblogs.com/OliverQin/p/12222619.html

异常处理的完整语法:

实际应用--此处用在对Excel文件的判断中:

#coding=gbk
import os
import xlrd

current_path=os.path.dirname(__file__)
excel_path=os.path.join(current_path,'../testcase.xlsx')

def read_excel_date_convert_case_info(excel_path):
try:
all_case_info = []
workbook = xlrd.open_workbook(excel_path)
sheet = workbook.sheet_by_index(1) ##修改这个下标可触发下标越界
for i in range(1,sheet.nrows):
case_info = []
for j in range(0,sheet.ncols):
case_info.append(sheet.cell_value(i,j))
all_case_info.append(case_info)
return all_case_info
##异常按照从上至下的顺序执行
except FileNotFoundError as e:
print("文件未找到")
except IndexError as e:
print("下标越界")
except Exception as e: #继承Exception(异常父类),当不知道什么错误的时候弹出该错误
print("系统错误")

#顶层代码调试
if __name__ == '__main__':
current_path = os.path.dirname(__file__)
excel_path = os.path.join(current_path, '../testcase.xlsx') #修改这个文件路径触发文件未找到异常
cases=read_excel_date_convert_case_info(excel_path)
原文地址:https://www.cnblogs.com/123anqier-blog/p/12725019.html