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
def reporterror(x):
if x == None:
raise NameError
print x
try:
reporterror(None)
except NameError:
print 'x == None'
#输出:
x == None
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
--------------------------------------
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