python 教程 第十一章、 异常
2013-07-23 17:03
218 查看
第十一章、 异常
1) try/except/else格式
except参数说明:
except: Catch all (or all other) exception types.
except name: Catch a specific exception only.
except name as value: Catch the listed exception and its instance.
except (name1, name2): Catch any of the listed exceptions.
except (name1, name2) as value: Catch any listed exception and its instance.
else: Run if no exceptions are raised.
finally: Always perform this block.
2) try/finally格式
3) try/except/else/finally通用格式
4) assert语句
用来声明某个条件是真的,并且在它非真的时候引发一个错误
assert len('abc') < 1
5) raise引发异常
1) try/except/else格式
try:
s = raw_input('--> ')
except EOFError:
print 'Why did you do an EOF on me?'
except:
print 'Error occurred.'
else:
print 'Done'
except参数说明:
except: Catch all (or all other) exception types.
except name: Catch a specific exception only.
except name as value: Catch the listed exception and its instance.
except (name1, name2): Catch any of the listed exceptions.
except (name1, name2) as value: Catch any listed exception and its instance.
else: Run if no exceptions are raised.
finally: Always perform this block.
2) try/finally格式
try:
fd=open("have-exists-file", "r")
finally:
fd.close()
3) try/except/else/finally通用格式
try:
main-action
except Exception1:
handler1
except Exception2:
handler2
...
else:
else-block
finally:
finally-block
4) assert语句
用来声明某个条件是真的,并且在它非真的时候引发一个错误
assert len('abc') < 1
5) raise引发异常
class ShortInputException(Exception):
def __init__(self, length):
Exception.__init__(self)
self.length = length
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s))
except ShortInputException, x:
print 'Exception: length %d ' % (x.length)
else:
print 'No exception.'
相关文章推荐
- python 教程 第十一章、 异常
- python 教程 第十一章、 异常
- python 教程 第十一章、 异常
- Python学习教程(八)——异常
- 简明python教程 --C++程序员的视角(七):异常
- Python基础教程——8 异常
- 【Python基础教程】第8章 异常
- 简明Python3教程 15.异常
- 简明Python3教程 15.异常
- <<Python基础教程>>学习笔记 | 第08章 | 异常
- Python基础教程——8 异常
- python基础教程共60课-第36课异常处理
- python教程22--《异常》
- 详解在Python中处理异常的教程
- Python教程之七-----错误和异常
- Python 教程阅读笔记(七):错误和异常
- 简明Python教程 12)输入输出 13)异常
- 简明Python教程学习笔记_8_异常
- python基础教程总结7——异常
- python基础教程_学习笔记10:异常