异常处理在任何一门编程语言里都是值得关注的一个话题,良好的异常处理可以让你的程序更加健壮,清晰的错误信息更能帮助你快速修复问题。在Python中,和不部分高级语言一样,使用了try/except/finally语句块来处理异常,如果你有其他编程语言的经验,实践起来并不难。
异常处理语句 try...excpet...finally
实例代码
defdiv(a, b):
try:
print(a / b)
exceptZeroDivisionError:
print("Error: b should not be 0 !!")
exceptExceptionase:
print("Unexpected Error: {}".format(e))
else:
print('Run into else only when everything goes well')
finally:
print('Always run into finally block.')
# tests
div(2,0)
div(2,'bad type')
div(1,2)
# Mutiple exception in one line
try:
print(a / b)
except(ZeroDivisionError, TypeError)ase:
print(e)
# Except block is optional when there is finally
try:
open(database)
finally:
close(database)
# catch all errors and log it