zoukankan      html  css  js  c++  java
  • python 异常知识点

    raise from

    python 在3.0 之后引入了raise from 表达式:

    raise exception from otherexception

    当使用该语法时,第二个表达式指定了另一个异常类或实例,它会附加到引发异常的__cause__属性

    注意:

    python3.0不再支持raise Exc,Args形式,而该形式在Python2.6中仍然可用,在Python3.0中,使用 raise Exc(Args)调用。

    with  as

    with语句格式:

    with expression [as variable]:
        with-block

    variable是expression执行后返回的对象引用。

    with as 作用是先执行启动程序,然后执行代码块,执行终止程序代码,无论该代码块是否引发异常。

    例如:

    myfile  =  open(r'C:miscdata')
    
    try:
        for line in myfile:
              print(line)
    finally:
          myfile.close

    可以使用:

    with open(r'C;miscdata') as myfile:
         for line in myfile:
               print(line)

    自定义环境管理协议

    就是自定义可以接入with语句的对象。

    with语句实际工作方式:

    1、计算表达式,所得到的对象称为环境管理器,它必须有__enter__和__exit__方法。

    2、环境管理器的__enter方法被调用,如果as语句存在,则返回值会被赋值给as子句中的变量

    3、代码块中嵌套代码会被执行。

    4、如果with引发异常,__exit__(type, value, traceback)方法会被调用,如果此方法返回值为假,则异常会被重新触发,否则,异常会被终止。正常情况下,应该重新触发异常,这样的话才能传递到with语句之外。

    5、如果with代码块没有引发异常,__exit__方法依然会被调用,其type、value、traceback都会以None传递。

    例:

    class TraceBlock:
        def message(self, arg):
            print('running',arg)
        
        def __enter__(self):
            print('starting with block')
            return self
        
        def __exit__(self, exc_type, exc_value, exc_th):
            if exc_type is None:
                print('exited normally
    ')
            else:
                print('raise an exception!', exc_type)
                return False
            
    with TraceBlock() as action:
        action.message('test 1')
        print('reached')
        
    with TraceBlock() as action:
        action.message('test2')
        raise TypeError
        print('not reached')

    执行结果:

    starting with block
    ('running', 'test 1')
    reached
    exited normally
    
    starting with block
    ('ruTraceback (most recent call last):
      File "D:workspaceaptanapythonTest	estcomcycygTraceBlock.py", line 27, in <module>
        raise TypeError
    TypeError
    nning', 'test2')
    ('raise an exception!', <type 'exceptions.TypeError'>)
  • 相关阅读:
    后期生成事件命令copy /y
    SevenZipShaper压缩类
    vs2017
    WCF路由服务
    微服务--
    各种流程图的绘画网路工具 processon
    ROC 准确率,召回率 F-measure理解(转载)
    Unix OpenCV安装
    转载:tar 解压缩命令~
    cppreference经验总结
  • 原文地址:https://www.cnblogs.com/beiyeren/p/3897957.html
Copyright © 2011-2022 走看看