常见的异常:
处理单个异常
#!/usr/bin/env Python# coding=utf-8class Calculator(object): is_raise = False def calc(self, express): try: return eval(express) except ZeroDivisionError: if self.is_raise: print "zero can not be division." else: raise #作为单独一个语句。它的含义是将异常信息抛出if __name__ == "__main__": c = Calculator() c.is_raise = True print c.calc("8/0")
运行结果:
处理多个异常
#!/usr/bin/env Python# coding=utf-8while 1: print "this is a division program." c = raw_input("input 'c' continue, otherwise logout:") if c == 'c': a = raw_input("first number:") b = raw_input("second number:") try: print float(a)/float(b) print "*************************" except ZeroDivisionError: print "The second number can't be zero!" print "*************************" except ValueError: print "please input number." print "************************" else: break
可以加一个else语句
#!/usr/bin/env Python# coding=utf-8while 1: try: x = raw_input("the first number:") y = raw_input("the second number:") r = float(x)/float(y) print r except Exception, e: print e print "try again." else: break
这样执行如果没有异常就退出
也可以在最后添加一个finally语句,综合起来异常表达式:
try: do somethingexcept: do somethingelse: do somethingfinally do something