Skip to content

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()