zoukankan      html  css  js  c++  java
  • 异常

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

    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)
  • 相关阅读:
    centos7
    aaa
    20199122 2019-2020-2 《网络攻防实践》第三周作业
    20189304李小涛网络攻防第二周作业
    20189304《网络攻防》第一周作业
    2019-2020-2 20199137 《网络攻防实践》第三次作业
    容器抓包方法
    打印输出10分钟日志内容
    linux shell 检查脚本参数
    Structure needs cleaning(结构需要清理)解决
  • 原文地址:https://www.cnblogs.com/rongpeng/p/12589713.html
Copyright © 2011-2022 走看看