try except else finally in Python
usage of try except else finally
关键字 | 功能 |
---|---|
try | 尝试运行 |
except | 捕获try块有可能抛出的某些异常 |
else | 如果try块代码没有发生异常,那么else块就会运行 |
finally | 无论try块是否抛出异常,finally块都会得到运行 |
#!/usr/bin/env python
import json
UNDEFINED = object ()
def divide_json(path):
print('* Opening file')
handle = open(path, 'r+') # May raise OSError
try:
print('* Reading data')
data = handle.read() # May raise UnicodeDecodeErro
print('* Loading JSON data')
op = json.loads(data) # May raise ValueError
print('* Performing calculation')
value = (op['numerator'] / op['denominator']) # May raise ZeroDivisionError
except ZeroDivisionError as e:
print('* Handling ZeroDivisionError')
return UNDEFINED
else:
print('* Writing calculation')
op['result'] = value
result = json.dumps(op)
handle.seek(0) # May raise OSError
handle.write(result) # May raise OSError
return value
finally:
print('* Calling close()')
handle.close() # Always run
if __name__ == "__main__":
divide_json("try.json")
use with instead
from threading import Lock
lock = Lock()
with lock:
## do something
equivalent to
lock.acquire()
try:
## do something
finally:
lock.release()
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.me
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No privacy information is collected here