异常处理:
try ...except try代码块放置容易发生异常的语句:except代码块放置处理异常的语句
try ...except...finally finally代码快是任何时候都会执行的;通常用于关闭系统的资源
- try:
- f = open('db100.txt','r')
- try:
- a = f.write('aa')
- print a
- except:
- print 'write error'
- finally:
- f.close()
- print 'close file'
- except:
- print 'open error'
- 输出:
- write error
- close file
raise 抛出异常;
- def reporterror(x):
- if x == None:
- raise NameError
- print x
- try:
- reporterror(None)
- except NameError:
- print 'x == None'
- #输出:
- x == None
自定义异常:
必须继承于Exception类
类名以Error结尾
自定义异常使用raise语句引发,而且只能通过手工引发:
Python pass 语句
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
- class MyError(Exception):
- pass
- def reporterror(x):
- if x == None:
- raise MyError()
- print x
- try:
- reporterror(None)
- except MyError,error:
- print 'x == None'
- #输出:
- x == None
- --------------------------------------
assert:语句用于测试某个条件表达式为真,即认为测的表达式永远为真,如果断言失败,会引发AssertionError异常
- str = 'hello'
- try:
- #x = 10/0
- assert len(str) == 3
- except AssertionError,x:
- print 'assert error',x
- 输出:
- assert error
异常信息:
str = 'hello'
- try:
- x = 10/0
- assert len(str) == 3
- except AssertionError,x:
- print 'assert error',x
- except Exception ,ex:
- print ex
- 输出:
- integer division or modulo by zero