python中的异常类型处理
来源:互联网 发布:c语言编译器win10 编辑:程序博客网 时间:2024/06/06 20:19
3、异常和函数
在函数内引发异常时,它就会被传播到到函数调用的地方(对于方法也是一样的)
>>> def faulty():raise Exception('Something is wrong')>>> def ignore_expection():faulty()>>> def handle_excepton():try:faulty()except:print 'Exception handled'>>> ignore_expection()Traceback (most recent call last): File "<pyshell#252>", line 1, in <module> ignore_expection() File "<pyshell#245>", line 2, in ignore_expection faulty() File "<pyshell#242>", line 2, in faulty raise Exception('Something is wrong')Exception: Something is wrong
可以看到,faulty中产生的异常通过faulty和ignore_exception传播,最终导致了堆栈跟踪。同样地,它也传播了handle_exception,但在这个函数中被try/except语句处理。
>>> def describePerson(person):print 'Description of',person['name']print 'Age:',person['age']try:print 'Occupation:',person['occupation']except KeyError:pass>>> describePerson({'name':'Throatwobbler','age':42})Description of ThroatwobblerAge: 42Occupation:>>>
>>> def describePerson(person):print 'Description of',person['name']print 'Age:',person['age']try:print 'Occupation:'+ person['occupation']except KeyError: #是捕获键值不存在时pass>>> describePerson({'name':'Throatwobbler','age':42})Description of ThroatwobblerAge: 42>>>
注:这里在打印职业时,使用加号而不是逗号。否则字符串'Occupaton:'在异常引发之前就会被输出。
查看某对象是否有write属性
try:object.writeexcept AttributeError:print 'The object is not writeable'else:print 'The object is writeable'
- python中的异常类型处理
- Python中的异常类型
- Python中的异常类型
- Python中的异常类型
- Python中的异常类型
- Python中的异常处理
- python中的异常处理
- python中的异常处理
- python中的异常处理
- python 中的异常处理
- python中的异常处理
- Python中的异常处理
- python 中的异常处理
- python中的异常处理
- Python中的异常处理
- Python中的异常处理
- Python中的异常处理
- Python异常处理和异常类型
- 大学的你,到底要学习什么?
- oracle job详解
- Tiny6410开发板linux启动错误 /init: line 102: can't open /r/dev/console: no such file 的解决方法
- AWR(Automatic Workload Repository)——概述(1)!
- 刚毕业的菜鸟,与其挤破头脑去大公司,还不如去小公司锻炼锻炼
- python中的异常类型处理
- 重新配置数据库的密码
- C++笔/面试
- 浅谈PCA(2)
- Class com.googlecode.jsonplugin.JSONWriter can not access a member of class*
- Ajax Control Toolkit中CalendarExtender(日期)控件显示中文的设定
- 传奇私服代码公布全集(3
- 挂载u盘 改天挂载dvd和移动硬盘
- Connection strings for SQL Server 2008