python 异常处理
异常处理
def demo():
try:
1 / 0
except Exception as e:
print(type(e)) #<class 'ZeroDivisionError'>
自定义异常
class CustomError(Exception):
pass
异常链
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
问题
-
对于
demo
而言, 他的异常是什么?def wapper(): try: demo() except Exception as e: # print(e.__cause__, type(e.__cause__)) print("error") print(e) print("end") <class 'ZeroDivisionError'> error end
是的, 结果为空, 因为此时 e 为 CustomError, 并没有写入 args
-
对于上面的
wapper
来说, 如何得到真实的 error, 即 1/0 (ZeroDivisionError)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