Python核心编程读笔 9: 异常
2015-11-15 14:28
691 查看
[b]第10章 异常[/b]
[b]一、异常[/b]
1 检测和处理异常
(1)try-except语句
try:
try_suite #监控这里的异常
except Exception[, reason]:
except_suite #异常处理代码
(2)“带有多个except的try语句”和“处理多个异常的except语句”
(3)捕获所有异常
try:
:
except Exception, e:
# error occurred, log 'e', etc.
也可以用裸except语句(不推荐):
try:
try_suite;
except:
# error occurred, log 'e', etc.
(4)异常参数
(5)else子句和finally子句
(6)try-except-else-finally:厨房一锅端
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2, Exception3, Exception4):
suite_for_Exceptions_2_3_and_4
except Exception5, Argument5:
suite_for_Exception5_plus_argument
except (Exception6, Exception7), Argument67:
suite_for_Exceptions6_and_7_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite
2 上下文管理
with语句:
with context_expr [as var]:
with_suite
举例:
with open('/etc/passwd', 'r') as f:
for eachLine in f:
# ...do stuff with eachLine or f...
注:无论的在这一段代码的开始,中间,还是结束时发生异常,会执行清理的代码,此外文件仍会被自动的关闭.
3 触发异常
raise [SomeException [, args [, traceback]]]
4 标准异常
[b]二、断言[/b]
assert expression[, arguments]
[b]一、异常[/b]
1 检测和处理异常
(1)try-except语句
try:
try_suite #监控这里的异常
except Exception[, reason]:
except_suite #异常处理代码
(2)“带有多个except的try语句”和“处理多个异常的except语句”
(3)捕获所有异常
try:
:
except Exception, e:
# error occurred, log 'e', etc.
也可以用裸except语句(不推荐):
try:
try_suite;
except:
# error occurred, log 'e', etc.
(4)异常参数
(5)else子句和finally子句
(6)try-except-else-finally:厨房一锅端
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2, Exception3, Exception4):
suite_for_Exceptions_2_3_and_4
except Exception5, Argument5:
suite_for_Exception5_plus_argument
except (Exception6, Exception7), Argument67:
suite_for_Exceptions6_and_7_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite
2 上下文管理
with语句:
with context_expr [as var]:
with_suite
举例:
with open('/etc/passwd', 'r') as f:
for eachLine in f:
# ...do stuff with eachLine or f...
注:无论的在这一段代码的开始,中间,还是结束时发生异常,会执行清理的代码,此外文件仍会被自动的关闭.
3 触发异常
raise [SomeException [, args [, traceback]]]
4 标准异常
[b]二、断言[/b]
assert expression[, arguments]
相关文章推荐
- python MySQLdb连接mysql失败问题
- 官方转载=》python2到3的库的变动
- python 中类的重载以及logging中的level
- python for 循环 一个 list 获取index
- python实现素数筛选
- 《用Python玩转数据》学习笔记第3周Part1
- Python学习笔记008_类_对象_继承_组合_类相关的BIF
- [问与答]Python 中 __all__ 的作用 ?
- [问与答]Python 中 __all__ 的作用 ?
- Python logging模块使用记录
- python 11期 第三天
- Python多进程并发操作中进程池Pool的应用
- Python 文档风格
- Python学习笔记007_图形用户界面(EasyGui)
- Eclipse python 插件 离线安装
- 第一个python程序hello.py
- 5. 数据类型库
- Python学习笔记006_异常_else_with
- Python3.5安装numpy,SciPy后,出现ImportError
- sublime Text文本编辑器在python环境下控制台输不出中文