异常处理与内置异常
student = {'name': 'Peter', 'age': 20, 'scores': [99, 88, 77]}
#print(student['name'])
#print(student.get('name'))
name = studnet['Name']
#print(name) #抛出KeyError异常
#print(student['scores'][3]) #IndexErroe错误、以上两个都是python内置的异常
try \ except
try:
name = student['name']
name = student['Name']
print(name)
last_score = student['score'][2]
last_score = student['score'][3]
print(last_score)
x = 5
z = x / 0
print(z)
#知道单个错误
#except KeyError:
#print('键错误!')
#except IndexErroe:
# print('索引错误!')
#多个错误可以放进()
#except (KeyErroe, IndexError):
# print('有键错误或索引错误')
#不知道发生什么错误用Exception
#except Exception: #Exception异常类的基类
# print('有错误!')
except ZerDivisionError as err:
print(err) #显示原本错误信息
print('除零错误')
# raise #捕获到异常 并抛出
else:
print('没有异常发生时执行代码!')
-------------------------------------------------------------------
>>>x = o
>>>raise NameError
显示NameError异常信息
>>>raise NameError('人为抛出的异常')
NameError: 人为抛出的异常
try \ finally
x = 20
try:
x += y
print(x)
finally: #不管有没有遇到异常都执行finally内程序
print('程序执行结束!')
f = open('data.txt', 'r', encoding='utf8')
try:
txt = f.read{}
print(txt)
except Exception:
pass
finally: #不管程序有没有异常文件都关闭、确保文件关闭
f.close()