zoukankan      html  css  js  c++  java
  • python 异常处理

    python中特殊的异常处理

    通常Exception能捕捉所有异常,但这些异常必须为python内部自定义的异常(并且不包括BaseException);若程序中抛出自定义异常,或者BaseException则该异常不能被Exception捕捉;但可以被BaseException或者不带参数的except捕捉

    class CustomException(BaseException):
        pass
    try:
        raise CustomException('an error accured')
    except Exception as e:
        print(f"catch exception {e}")
    
    # 运行结果
    Traceback (most recent call last):
      File "C:/Users/wyx/Desktop/test.py", line 108, in <module>
        raise CustomException('an error accured')
    CustomException: an error accured
    
    class CustomException(BaseException):
        pass
    
    try:
        raise CustomException('an error accured')
    except BaseException as e:
        print(f"catch exception '{e}'")
    
    # 运行结果
    catch exception 'an error accured'
    

    with在异常发生时自动执行对象的__exit__方法

    使用with进行上下文管理时,只要__enter__方法已经执行完成,无论执行过程中是否抛出异常,__exit__方法均会执行

    class A:
        def __enter__(self):
            # raise BaseException('error in content')
            print('Enter class A')
    
        def __exit__(self,Type, value, traceback):
            print('exit class A')
    
    with A():
        raise BaseException('error in content')
    
    # 结果
    Enter class A
    exit class A
    Traceback (most recent call last):
      File "C:/Users/wyx/Desktop/test.py", line 98, in <module>
        raise BaseException('error in content')
    BaseException: error in content
    
  • 相关阅读:
    java编程规范
    Servlet生命周期
    BBS
    Hibernate主键自增策略
    MyBatis举例以及连接数据库过程
    myBatis框架的配置部分
    持续集成
    2017-02-23 .NET Core Tools转向使用MSBuild项目格式
    记录表TABLE中 INDEX BY BINARY_INTEGER 的作用
    什么是 BIND 变量?
  • 原文地址:https://www.cnblogs.com/yxwxy/p/10444310.html
Copyright © 2011-2022 走看看