Python异常的使用
伪代码:
try:
出错部分的代码......
except Exception as e:
print '404网页' #Exception是所有错误类型的父类,包括所有出错信息
finally:
操作(不管是否出错,finally都执行)
我的例子程序:
#import os def func(a,b): return a/b if __name__ == "__main__": try: func(3,0) except Exception as e: print('404ERROR,to the new index page.....') finally: print('Finally,no error!') print('end')
def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: print('Error:', e) finally: print('finally...')
自定义抛出的异常:(较少使用)http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143191375461417a222c54b7e4d65b258f491c093a515000
# err_raise.py class FooError(ValueError): pass def foo(s): n = int(s) if n==0: raise FooError('invalid value: %s' % s) return 10 / n foo('0')