python里面使用try-except-else-finally来处理异常,流程是:先处理try内的部分,有异常则进入except分支,否则进入else分支,但不管有无异常肯定会进入finally分支。这里结合以前java处理异常的流程,写了几个例子,做一个总结:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#test 1
def main():
try:
print "In try block"
raise "exception"
except:
print "In exception block"
else:
print "in else block"
finally:
print "In finally block"
if __name__ == "__main__":
main()
输出:
In try block
In exception block
In finally block
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#test 2
def main():
try:
print "In try block"
except:
print "In exception block"
else:
print "in else block"
finally:
print "In finally block"
if __name__ == "__main__":
main()
In try block
in else block
In finally block
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#test 3
def main():
try:
print "In try block"
return
except:
print "In exception block"
else:
print "in else block"
finally:
print "In finally block"
if __name__ == "__main__":
main()
输出:
In try block
In finally block
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
注意: 在情况3中,else分支的语句是不被执行的!!