Skip to content

try except else finally in Python

usage of try except else finally

Keyword Function
try Attempt to run
except Catch certain exceptions that might be thrown by the try block
else If no exceptions occur in the try block, then the else block will run
finally The finally block will run regardless of whether the try block throws an exception or not
#!/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