Error and Exception Handling · 3 / 20 Theory

else, finally and the complete structure

You already know try and except. The complete structure has two more blocks, else and finally, which give you control over what happens when everything goes well and over what must always happen.

The complete structure

try:
    # code that may fail
except ErrorType:
    # what to do if it fails
else:
    # runs only if there was NO exception
finally:
    # runs ALWAYS

else: when everything went well

The else block runs only if the try finished without exceptions. It is used to separate the code that may fail from the code that depends on it having gone well:

try:
    number = int(input())
except ValueError:
    print("Invalid number")
else:
    print(f"Double is {number * 2}")

You could put the print inside the try, but this way it is clear which line may fail and you avoid accidentally catching exceptions from code you did not want to watch.

finally: no matter what

finally always runs: whether there was an exception or not, and even if inside the try there is a return or an exception that nobody catches. It is the place for cleanup tasks: closing a file, releasing a resource, showing a final message.

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    finally:
        print("End of calculation")

print(divide(10, 2))
# End of calculation
# 5.0
print(divide(1, 0))
# Cannot divide by zero
# End of calculation
# None

Notice the order: even though the try does return, the finally runs before the function returns the value.

What runs in each case

Situationtryexceptelsefinally
No errorto the endnoyesyes
Caught errorup to the erroryesnoyes
Uncaught errorup to the errornonoyes (and then the error continues)

with: the automatic finally

Closing a file is the classic use of finally:

f = open("data.txt", "r", encoding="utf-8")
try:
    content = f.read()
finally:
    f.close()        # closed even if read() fails

Since it is so common, Python offers with, which is equivalent to that try/finally:

with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()
# here the file is already closed, whether there was an error or not

Practice with Calculator with finally.