异常处理
1"""
2Author: wangy325
3Date: 2024-07-16 21:07:13
4Description: 异常的处理和抛出, else语句, finally语句, 异常组
5"""
6
7
8class B(Exception):
9 pass
10
11
12class C(B):
13 pass
14
15
16class D(C):
17 pass
18
19
20for els in [B, C, D]:
21 try:
22 raise els
23 except D:
24 print('D')
25 except C:
26 print('C')
27 except B:
28 print('B')
29'''
30展示了异常的传递和匹配:
31抛出的异常是exception捕获异常的子类可以匹配上, 反之不行
32这很好理解啊
33`raise`语句相当于主动抛出异常
34`else`子句只有在try语句没有发生异常时才执行.
35所以, `else`语句可以避免意外捕获一些非try块引发的异常.
36'''
37a, b = 1, '2'
38try:
39 c = a + b
40except TypeError as e:
41 print(f'{e.__class__}: {e} ')
42else:
43 print(f'else block: {c}')
44
45# But, how about a exception occurs in else sub-sentence?
46# Solution 1: use extra try...exception to handle that.
47# Solution 2: use finally sub-sentence to re-raise exception.
48# Best way is, make sure your else sub-sentence clean.
49try:
50 print('try ok!')
51except SystemError:
52 print('never mind')
53else:
54 try:
55 2 / 0
56 except ZeroDivisionError as e:
57 print(f'else error: {e}')
58
59
60def how_finally_works(x, y):
61 try:
62 return x / y
63 except ZeroDivisionError as exp:
64 print(f"{exp}: can not divide by 0")
65 return 0
66 finally:
67 print('finally...')
68 return -1
69
70
71# 返回finally子句的值
72print(how_finally_works(2, 3), end='\n---------\n')
73print(how_finally_works(2, 0), end='\n---------\n')
74print(how_finally_works('a', 'b'), end='\n---------\n')
75'''
761) finally 子句一定会执行(调用1,2,3)
772) finally 子句的返回值会覆盖try块的返回值(调用2)
783) finally 子句有return语句, 会覆盖未处理的异常(调用3)
79
80他么的, 究竟是谁会在finally块中写返回值啊
81'''
82
83
84def how_finally_works2():
85 try:
86 slt = []
87 for i in reversed(range(-1, 3)):
88 if i < 0:
89 break
90 slt.append(10 / i)
91 # return slt
92 except ZeroDivisionError as e:
93 print(f'{e.__class__}: {e}')
94 else:
95 print('else here.')
96 return slt
97 finally:
98 print('finally here.')
99
100
101print(how_finally_works2())
102'''
1031. 如果try子句中存在return语句, 且没有发生异常, 则else子句不再执行.
1042. 如果try子句中存在return语句, 发生异常且被捕获, finally语句在return之前执行
105'''
106
107print('-----ExceptionGroup-----')
108
109
110def f():
111 es = [OSError('error 1'), SystemError('error 2')]
112 raise ExceptionGroup('there are problems: ', es)
113
114
115f()
116'''
117ExceptionGroup 是3.11之后引进的新特性
118'''