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
阅读全文
0 0
- Python 异常处理 (try 和 except)
- Python 异常处理 try/except
- python异常处理try...except
- Python 异常处理 Python 基础教程 try..except
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- python中的异常处理 try..except
- Python异常处理try...except、raise
- Python---异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- python try...except....else...finally处理异常
- try,except异常处理
- Python 异常 try except
- Python3:异常处理,try...except
- 异常处理try...except、raise
- python错误和异常处理的简单操作实例(try-except)
- python 异常 try-except句型
- DER编码规则
- 算法期中——最近的0
- 【android逆向笔记】(七)从博客找到的可以练习的apk逆向练习第二款
- 【Scikit-Learn 中文文档】预测延迟 / 预测吞吐量 / 技巧和窍门
- 逻辑回归 logistic regression 代价函数导数求解过程
- Python 异常处理 (try 和 except)
- eclipse 常用快捷键
- luogu 1000超级玛丽
- 【Scikit-Learn 中文文档】使用 scikit-learn 介绍机器学习
- js异常 missing ) after argument list 解决方案
- Algorithm之路一:Two Sum
- Android.mk和Application.mk配置参数详解
- 【Scikit-Learn 中文文档】机器学习: scikit-learn 中的设置以及预估对象
- 问题 D: 输入入门(3)