程序员

Python中的异常处理(不定时更新)

2018-10-09  本文已影响0人  Drycountry233

1 异常的定义

程序运行期检测到的错误被称为异常exception,它以错误信息的形式展现。python提供了异常处理机制(exception-handling machnism),采用异常对象exception objects来代表异常情况。当出现错误时,通过调用Traceback栈的形式将异常对象抛出/提出(raise),同时程序停止运行。
为保证程序出错后可继续执行,需要对错误进行捕捉和处理。因为当使用者使用程序时,程序出现异常后终止并报出tracebacks显然是不合理的(他们可能并不懂哪里出了问题);更危言耸听一点,心怀不轨的人可能会根据traceback信息知悉程序存在的漏洞并加以破坏。
举例:输入两个数字,打印二者的商。当作为除数的数字为0时,会提出异常对象ZeroDivisionError,它的前面指明了产生异常的位置:

num1 = int(input("Enter the first number : "))
num2 = int(input("Enter the second number : "))
print(num1/num2)
------------------------------在终端中运行------------------------------
Enter the first number : 10
Enter the second number : 0
Traceback (most recent call last):
  File "e:/PYTHON_EX/test.py", line 11, in <module>
    print(num1/num2)
ZeroDivisionError: division by zero

2 基本语法

2.1 try-except语句

如果可预见某类异常会发生,可采用 try-except 语句进行处理,将可能出错的语句“包裹”起来。,它的基本语法如下:

try:
    try_statements # Python tries to run the code here.
except some_exception1:
    e1_statements # if the code results in a particular kind of exception, run the statements here.
except some_exception2:
    e2_statements # if the code results in a particular kind of exception, run the statements here.

some_exception可以是单个异常类型,或是由多个异常类型组成的元祖。
执行流程:

  1. 如果try后的语句运行无误,那么python继续执行 try-except 后面的语句;
  2. 如果try后的语句运行出现错误,那么python查找与错误匹配的except语句块(可以有多个):
    • 匹配成功,在运行该except语句块中的语句(如进行较友好的错误提示)后继续执行 try-except 后面的语句;
    • 匹配失败,提出异常,程序终止。

在前面例子基础上增加 try-except 语句,如下:

try:
    num1 = int(input("Enter the first number : "))
    num2 = int(input("Enter the second number : "))
    print(num1/num2)
except ZeroDivisionError:
    print("The second number shouldn't be zero.")
except ValueError:
    print("Number required.")
------------------------------在终端中运行------------------------------
Enter the first number : 10
Enter the second number : 0
The second number shouldn't be zero.
或
Enter the first number : a
Number required.

2.2 try-except-else语句

try后的语句执行无误,则依次执行else后的语句、try-except-else后的语句。else后的语句的执行依赖于try后语句的成功执行。
语句执行流程:

  1. 如果try后的语句运行无误,那么python先运行else后的语句,再执行 try-except-else 后面的语句;
  2. 如果try后的语句运行出现错误,那么python查找与错误匹配的except语句块:
    • 匹配成功,在运行该except语句块中的语句(如进行较友好的错误提示)后继续执行 try-except 后面的语句;
    • 匹配失败,提出异常,程序终止。

如下所示:

try:
    num1 = int(input("Enter the first number : "))
    num2 = int(input("Enter the second number : "))
    answer = num1/num2
except ZeroDivisionError:
    print("The second number should not be zero.")
except ValueError:
    print("A number is required.")
else:
    print("The answer is {}.".format(answer))
print("It ends here.")
------------------------------在终端中运行------------------------------
Enter the first number : 10
Enter the second number : 5
The answer is 2.0.
It ends here.

2.3 try-except-else-finally

完全体出现。finally后的语句无论如何都会执行。不再详述。

2.4 raise语句

使用raise语句是,后面不跟参数可以报出预期外的异常;raise后跟上某种异常类型可在出现错误时报出该异常。

try:
    1/a
except ZeroDivisionError:
    print("The second number should not be zero.")
except:
    raise
------------------------------在终端中运行------------------------------
NameError: name 'a' is not defined
try:
    1/a
except ZeroDivisionError:
    print("The second number should not be zero.")
except:
    raise FileNotFoundError # 举例
------------------------------在终端中运行------------------------------
Traceback (most recent call last):
  File "e:/PYTHON_EX/test.py", line 6, in <module>
    raise FileNotFoundError
FileNotFoundError
上一篇下一篇

猜你喜欢

热点阅读