首页 > 技术文章 > 异常

rongpeng 2020-03-28 21:57 原文

 

异常的传递,会把异常返回调用处

 

try:
    11/0
    #open("xxx.txt")
    print("---1--------")
except (NameError,FileNotFoundError): #多种类型异常写一起时使用元组方式,具体异常
    print("如果没有捕获到异常后做的处理......")
except Exception as ret: #捕获所有异常,as可以看到具体异常
    print("如果用了Exception,意味着上面的except没有捕获到异常,这个except一定会捕获到")
    print(ret)
else:
    print("没有异常才会执行的功能")
finally:
    print("不管有没有异常都会执行")
print("----2-----")

自定义异常

class ShortInputException(Exception):
    """自定义异常"""
    def __init__(self, length, atleast):
        self.length = length
        self.atleast = atleast

def main():
    try:
        s = input('请输入 --> ')
        if len(s) < 3:
            #raise引发一个自定义的异常
            raise ShortInputException(len(s),3)
    except ShortInputException as result: #这个变量被绑定到了错误的实例
        print('ShortInputExcption:输入的长度是%d,长度至少是%d'%(result.length,result.atleast))
    else:
        print('没有发生异常')

main()

 

异常处理中抛出异常

class Test(object):
    def __init__(self, switch):
        self.switch = switch

    def calc(self, a, b ):
        try:
            return a/b
        except Exception as result:
            if self.switch:
                print("捕获开启,已捕获到了异常,信息如下:")
                print(result)
            else:
                #重新抛出异常,此时就不会被这个异常处理捕获,从而触发默认的异常处理
                raise #默认异常处理,由系统处理

a = Test(True)
a.calc(11,0)

print("------------------------")
a.switch = False
a.calc(11,0)

 

推荐阅读