try:
print 10 / 0
except ZeroDivisionError, e:
print "catched a ValueError:",e
上面的代码中,被除数是0,会引发ZeroDivisionError,运行上面的代码:
catched a ValueError: integer division or modulo by zero
如果一段代码可能跑出多个异常,try except也是可以处理的, 下面代码用来读取一个文件,并转换成整型输出
try:
f = open("d:/num.txt")
line = f.read(2)
num = int(line)
print "read num=%d" % num
except IOError, e:
print "catch error==:", e
except ValueError, e:
print "catch error==:", e
如果文件不存在,会捕捉到下面异常:
catch error==: [Errno 2] No such file or directory: 'd:/num.txt'
另外,如果读取的字符串不能转换成整型,则会捕捉到ValueError
catch error==: invalid literal for int() with base 10: 'd3'
try:
....
except:
....
else:
....
如果没有异常,执行else中的代码
try:
f = open("d:/num.txt")
line = f.read(2)
num = int(line)
print "read num=%d" % num
except IOError, e:
print "catch error==:", e
except ValueError, e:
print "catch error==:", e
else:
print "no error happend"
try:
try_code
finally:
do_finally
上面的try–finally按照如下规则执行:
try:
f = open("d:/num.txt")
line = f.read(2)
num = int(line)
print "read num=%d" % num
except IOError, e:
print "catch error==:", e
finally:
print "f close()"
f.close()
上面的程序,当读取到非法字符串时候,此时转换成整型会出错,此时finally语句块先执行,然后,将异常交给python解释器处理
try:
try_code
except:
except_code
else:
else_code
finally:
finally_code
上面的代码块会按照下面的规则来执行:
with context [as var]:
with_code
with open("d:/num.txt") as f:
for line in f.read():
print line
print "f is closed :",f.closed
class FileError(IOError):
pass
try:
raise FileError, "this is a fileerror"
except FileError, e:
print e
此时运行会打印如下:
this is a fileerror