I'm writing some software in python and had a question on the preferred coding style of python. Imagine you have a function that takes some raw data, decodes it to a dict and prints the key-value pairs
def printdata(rawdata):
data = decode(rawdata)
for key, value in data.items():
print(key, value)
This is all fine until decode starts throwing exceptions everywhere and the whole program comes crashing down. So, we use a try/catch block. But there are a couple ways of doing this and I'm wondering what method is preferred.
Everything inside
trydef printdata(rawdata): try: data = decode(rawdata) for key, value in data.items(): print(key, value) except ValueError: print("error")Only
decodeinsidetrywithreturndef printdata(rawdata): data = None try: data = decode(rawdata) except ValueError: print("error") return for key, value in data.items(): print(key, value)Only
decodeinsidetrywithifdef printdata(rawdata): data = None try: data = decode(rawdata) except ValueError: print("error") if data is not None: for key, value in data.items(): print(key, value)
All of these methods have some advantages and disadvantages and I don't know which one to pick, and whether it really matters.