kota's memex

try/except

Using a try/except block is a common way of doing error handling:

try:
    # Manually raise an error
    raise IndexError("This is an index error")
except IndexError as e:
    pass # Usually a bad idea, normally you should provide a recovery
except (TypeError, NameError):
    pass                 # Multiple exceptions can be processed jointly.
else:                    # Optional clause to the try/except block. Must follow
                         # all except blocks.
    print("All good!")   # Runs only if the code in try raises no exceptions
finally:                 # Execute under all circumstances
    print("We can clean up resources here")

with

Instead of try/finally to clean up resources you can use a with statement:

# Reading a file
with open("myfile.txt") as f:
    for line in f:
        print(line)

# Writing to a file
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w") as file:
    file.write(str(contents))

# Encoding json to a file
import json
with open("myfile2.json", "w") as file:
    file.write(json.dumps(contents))