断言
assert 条件
:条件为假时弹出异常AssertionError
try-except
try:
检测范围
except Exception[ as reason]:
出现异常(Exception)后的处理代码
例:
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError as reason:
print('文件出错,原因是:' + str(reason))
try-finally
如果try中没有错误,则跳过except执行finally;如果try中有错误,则先执行except再执行finally。
try:
f = open('test.txt')
print(f.read())
sum = 1 + '1'
except:
print('出错了')
finally:
f.close()
raise()
抛出一个异常
raise ZeroDivisionError
raise ZeroDivisionError('除数不能为0')
with
with会自动关闭文件
try:
with open('data.txt', 'w') as f:
for each_line in f:
print(each_line)
except OSError as reason:
print('文件出错,原因是:' + str(reason))