Python 异常处理 (try 和 except)

来源:互联网 发布:古琴尺寸数据图 编辑:程序博客网 时间:2024/06/06 17:50

Python 异常处理 (try 和 except)

       异常处理使程序能检测错误,处理它们,然后继续运行。
       当试图用一个数除以零时,就会发生 ZeroDivisionError.
example 1

def spam(divideBy):    return 42 / divideByprint(spam(2))print(spam(12))print(spam(0))print(spam(1))

=>
/usr/bin/python2.7 /home/strong/PycharmProjects/crash_course/numpy_function/exception_handling.py213Traceback (most recent call last):  File "/home/strong/PycharmProjects/crash_course/numpy_function/exception_handling.py", line 11, in <module>    print(spam(0))  File "/home/strong/PycharmProjects/crash_course/numpy_function/exception_handling.py", line 7, in spam    return 42 / divideByZeroDivisionError: integer division or modulo by zeroProcess finished with exit code 1


        根据错误信息中给出的行号,我们知道 spam()中的 return 语句导致了一个错误。错误可以由 try 和 except 语句来处理。那些可能出错的语句被放在 try 子句中。如果错误发生,程序执行就转到接下来的 except 子句开始处。可以将前面除数为零的代码放在一个 try 子句中,让 except 子句包含代码,来处理该错误发生时应该做的事。


example 2

def spam(divideBy):    try:        return 42 / divideBy    except ZeroDivisionError:        print('Error: Invalid argument.')print(spam(2))print(spam(12))print(spam(0))print(spam(1))

        如果在 try 子句中的代码导致一个错误,程序执行就立即转到 except 子句的代码。在运行那些代码之后,执行照常继续。
=>
/usr/bin/python2.7 /home/strong/PycharmProjects/crash_course/numpy_function/exception_handling.py213Error: Invalid argument.None42Process finished with exit code 0

        请注意, 在函数调用中的 try 语句块中, 发生的所有错误都会被捕捉。请考虑以下程序,它的做法不一样, 将 spam()调用放在语句块中

example 3

def spam(divideBy):    return 42 / divideBytry:    print(spam(2))    print(spam(12))    print(spam(0))    print(spam(1))except ZeroDivisionError:    print('Error: Invalid argument.')

=>
/usr/bin/python2.7 /home/strong/PycharmProjects/crash_course/numpy_function/exception_handling.py213Error: Invalid argument.Process finished with exit code 0

        print(spam(1))从未被执行是因为, 一旦执行跳到 except 子句的代码, 就不会回到 try 子句。 它会继续照常向下执行。


references

[1] (美) Al Sweigart (斯维加特) 著;王海鹏 译. Python编程快速上手:让繁琐工作自动化[M]. 北京:人民邮电出版社, 2016. 1-391


原创粉丝点击