Skip to content

try except else finally in Python

homepage-banner

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







Disclaimer
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback me#imzye.com, replace # with @