天池python训练营Day03
python语句异常的处理与相关函数的使用
try-except语句
try-except语句的主要作用是规范python程序运行过程中出现的异常与错误,使得在程序运行出现错误时仍能够保持python结构的合理性
try-except分为两个结构,try为所执行语句的结构,except为所执行语句错误的结构(注意语句的错误类型必须要声明)
示例其中一种错误类型的用法
// A code block
import requests #用到的模块需要导入
url='https://tianchi.aliyun.com/competition/gameList/coupleList' #此为网页的链接
try:
respost=requests.get(url) #解析网页代码
if respost.status_code == 200: #判断解析是否成功
return respost.json() #返回解析的HTML
except requests.ConnectionError: #try出现异常时,会触发except的错误类型
return None #没有返回
var foo = 'bar';
try-except-finally语句
finally的作用是在try出现错误,错误不属于except所显示的类型时,才会触发但他与except又有点不同,无论try是否发生错误它都会触发.
// A code block
import requests
url='https://tianchi.aliyun.com/competition/gameList/coupleList'
try:
respost=requests.get(url)
if respost.status_code == 200:
return respost.json()
except requests.ConnectionError:
return None
finally:
print('lucky') #try出不出错误都会触发
var foo = 'bar';
try-except-else语句
else语句在不发生except错误时才会执行
import requests
url='https://tianchi.aliyun.com/competition/gameList/coupleList'
try:
respost=requests.get(url)
if respost.status_code == 200:
return respost.json()
except requests.ConnectionError:
return None
else:
print(respost) #try不发生错误时执行