Python中如果程序执行出错,会在出错的地方停止。但是如果想要程序出错后还能正常执行,则需要使用try … except来处理异常。
try:
10/0
except Exception as e:
print('失败')
print(e)
else:
print('成功')
print('结束')
上例中因为已经处理了异常,所以print(‘失败’)、print(e)、print(‘结束’)语句都会被执行。
try:
10/0
except Exception as e:
print('失败')
raise e
else:
print('成功')
print('结束')
第二例中,捕获异常后使用raise e语句抛出异常,则程序停止运行,不会执行print(‘结束’)语句。