异常

异常
  异常就是在程序执行过程中发生的错误。当错误发生时,Python产生一个异常,异常可以被捕获和处理,异常可以用来避免程序崩溃。

为什么要使用异常?
  异常是一个便捷的处理错误的方法。如果一段代码执行时可能会产生错误,则可以使用异常来捕获错误,并处理错误,使程序的流程回归到正常,避免程序因出现错误而崩溃。

try...except
  捕获异常并对异常进行处理,最简单的方式是使用语句try...except。Python会先执行try与except之间的语句,执行过程中如果发生异常,则会跳转到except后面的语句。下面是一个例子:
try:
    print(5/0) # print-1
    print('This end of try.') # print-2
except:
    print("There's an exception.") # print-3
print('This end of try...except.') # print-4

  在上面的例子中,一共有4个print()语句,Python先执行print-1,因为除数不能为零,所有发生了错误。程序的执行的流程会跳转到except后的print-3,即跳过了print-2,不会执行print-2。执行完print-3后,继续执行print-4。最终的输出是:

There's an exception.
This end of try...except.

  除了捕获所有异常,还可以捕获指定的异常,例如:
# -*- coding: utf-8 -*-

try:
    print(5/0) # print-1
    print('This end of try.') # print-2
except ZeroDivisionError as e:
    print("There's an exception:", e) # print-3
print('This end of try...except.') # print-4

  程序的输出:

There's an exception: division by zero
This end of try...except.

  可以通过捕获异常的基类Exception,以获得异常的信息
# -*- coding: utf-8 -*-

try:
    print(5/0) # print-1
    print('This end of try.') # print-2
except Exception as e:
    print("There's an exception:", e) # print-3
print('This end of try...except.') # print-4

  程序的输出:

There's an exception: division by zero
This end of try...except.



raise
  可以使用raise抛出一个异常。raise会终止当前代码的执行,转而执行对应异常处理代码,当异常处理代码执行完成后,回到终止的地方继续执行。
# -*- coding: utf-8 -*-

try:
    raise ZeroDivisionError('Zero Division Error')
    print('This end of try.') # print-2
except Exception as e:
    print("There's an exception:", e) # print-3
print('This end of try...except.') # print-4

  程序的输出:

There's an exception: Zero Division Error
This end of try...except.



try...except...else
  如果try和except之间的语句没有产生了异常,则会执行else子句;如果产生了异常,则不会执行else子句。


try...except...finally和try...finally
    finally子句是可选的,与else相对应,无论是否产生异常都会执行finally子句。如果同时使用else和finally,需要确保else在finally之前。