-
Notifications
You must be signed in to change notification settings - Fork 0
/
item_13.py
executable file
·61 lines (48 loc) · 1.62 KB
/
item_13.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
#!/usr/bin/env python3
'''Item 13 from Effective Python'''
# Example 1
''' One common usage of try / finally is for reliably closing file handles '''
print('Example 1:\n==========')
handle = open('random_data.txt', 'w', encoding='utf-8')
handle.write('success\nand\nnew\nlines')
handle.close()
handle = open('random_data.txt') # May raise IOError
try:
data = handle.read() # May raise UnicodeDecodeError
finally:
handle.close() # Always runs after try
# Example 2
''' Use try / except / else to make it clear which exceptions will be handled
by your code and which exceptions will propagate up '''
print('\nExample 2:\n==========')
import json
def load_json_key(data, key):
try:
result_dict = json.loads(data) # May raise ValueError
except ValueError as e:
raise KeyError from e
else:
return result_dict[key] # May raise KeyError
# Example 3
''' Use try / except / else / finally when you want to do it all in one
compound statement '''
print('\nExample 3:\n==========')
UNDEFINED = object()
def divide_json(path):
handle = open(path, 'r+') # May raise IOError
try:
data = handle.read() # May raise UnicodeDecodeError
op = json.loads(data) # May raise ValueError
value = (
op['numerator'] /
op['denominator']) # May raise ZeroDivisionError
except ZeroDivisionError as e:
return UNDEFINED
else:
op['result'] = value
result = json.dumps(op)
handle.seek(0)
handle.write(result) # May raise IOError
return value
finally:
handle.close() # Always runs