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
    
  • 相关阅读:
    BZOJ 1207
    Poj 2096 Collecting Bugs (概率DP求期望)
    HDU 5159 Card (概率求期望)
    HDU 4649 Professor Tian (概率DP)
    HDU 4652 Dice (概率DP)
    HDU5001 Walk(概率DP)
    C++中的 Round(),floor(),ceil()
    HDU 5245 Joyful(概率题求期望)
    poj 3071 Football (概率DP水题)
    关于一个群号分解的最大质数的求法
  • 原文地址:https://www.cnblogs.com/yxwxy/p/10444310.html
Copyright © 2011-2022 走看看