【Python基础教程】第8章 异常

来源:互联网 发布:卓尔集团待遇 知乎 编辑:程序博客网 时间:2024/05/19 03:18

1.自定义异常:继承Exception

#1.自定义异常类#方法:从Exception类继承class SomeCustomException(Exception):pass
2.处理异常

#(1)捕捉异常:try/excepttry:    x = input('Enter the first number:')    y = input('Enter the second number:')    print x/yexcept ZeroDivisionError:    print "The second number couldm't be zero"#注:如果异常没有被捕捉,就会传递到函数调用的地方。#    如果一直没有被捕捉,会一直传到程序的最顶层。#    最终,在Trackback中打印输出。#(2)传递异常:raiseclass MuffledCalculator:    muffled = False    def calc(self, expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Division by zero is illegal'            else:                raise#将异常传递#(3)多个异常#(3.1)except ZeroDivisionError:print "......"except TypeError:print "......"#(3.2)except (ZeroDivisionError, TypeError), e:print e#(4):捕捉全部异常:仅仅使用except(很危险,不提倡使用)try:    x = input('Enter the first number:')    y = input('Enter the second number:')    print x/yexcept:    print "Something wrong happened.."#(5)try/except 和 elsewhile True:    try:        x = input('Enter the first number:')        y = input('Enter the second number:')        value = x/y        print 'x/y is', value    except Exception, e:        print "The input is invalid"        print "Please try again"    else:        break#注:except语句和else语句仅仅会执行一个。#    当发生异常,不执行else;当没有反生异常,执行else#(5)finallytry:    1/0except NameError:    print 'Unknown variable'else:    print 'That went well'finally:    print 'other things'

0 0
原创粉丝点击