-
Notifications
You must be signed in to change notification settings - Fork 49
/
try_finally_tutorial.py
73 lines (55 loc) · 1.33 KB
/
try_finally_tutorial.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def base_example_1():
try:
print("run_1")
except Exception:
print("Exception")
finally:
print("other code")
def example_1():
try:
print("run_1")
except Exception:
print("Exception")
return "re Exception"
finally:
print("other code")
def example_1_except():
try:
1 / 0
except Exception:
print("Exception")
return "re Exception"
finally:
print("other code")
def example_2_diff():
try:
print("run_1")
except Exception:
print("Exception")
return "re Exception"
print("other code")
def example_2_diff_except():
try:
1 / 0
except Exception:
print("Exception")
return "re Exception"
print("other code")
def example_file():
# better with as statement
myfile = open("test.txt", "w")
try:
# 1/0
myfile.write("data") # raises Exception
except Exception:
print("Exception")
finally:
print("close file")
myfile.close() # has run
if __name__ == "__main__":
print(base_example_1())
# print(example_1())
# print(example_1_except()) # -> has print("other code") ## important
# print(example_2_diff())
# print(example_2_diff_except()) # -> no print("other code")
# example_file()