try:
test_func()
except ZeroDivisionError:
print("Catch error in the main program")
子程序的try...except...结构无法处理相应的除以0的错误,所以错误被抛给上层的主程序。
如果try中没有异常,那么except部分将跳过,执行else中的语句。
finally是无论是否有异常,最后都要做的一些事情。
流程如下,
try->异常->except->finally
try->无异常->else->finally
抛出异常
我们也可以自己写一个抛出异常的例子:
print 'Lalala'
raise StopIteration
print 'Hahaha'
这个例子不具备任何实际意义。只是为了说明raise语句的作用。
StopIteration是一个类。抛出异常时,会自动有一个中间环节,就是生成StopIteration的一个对象。Python实际上抛出的,是这个对象。当然,也可以自行生成对象:
raise StopIteration()
总结
try: ... except exception: ... else: ... finally: ...
raise exception










