异常处理

1
2
3
4
5
def demo():
    try:
        1 / 0
    except Exception as e:
        print(type(e)) #<class 'ZeroDivisionError'>

自定义异常

1
2
class CustomError(Exception):
    pass

异常链

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class CustomError(Exception):
    pass


def demo():
    try:
        1 / 0
    except Exception as e:
        print(type(e)) #<class 'ZeroDivisionError'>
        raise CustomError() from e

<class 'ZeroDivisionError'>
Traceback (most recent call last):
  File "/Users/tiger/work/customer/dd.py", line 23, in demo
    1 / 0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/tiger/work/customer/dd.py", line 39, in <module>
    demo()
  File "/Users/tiger/work/customer/dd.py", line 26, in demo
    raise CustomError() from e
__main__.CustomError

问题

  1. 对于 demo 而言, 他的异常是什么?

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    def wapper():
        try:
            demo()
        except Exception as e:
            # print(e.__cause__, type(e.__cause__))
            print("error")
            print(e)
            print("end")
    
    
    <class 'ZeroDivisionError'>
    error
    
    end
    

    image-20211009200333580

    是的, 结果为空, 因为此时 e 为 CustomError, 并没有写入 args

  2. 对于上面的 wapper 来说, 如何得到真实的 error, 即 1/0 (ZeroDivisionError)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    def wapper():
        try:
            demo()
        except Exception as e:
            print(e.__cause__, type(e.__cause__))
            print("error")
            print(e)
            print("end")
    
    
    <class 'ZeroDivisionError'>
    division by zero <class 'ZeroDivisionError'>
    error
    
    end