Handling Exceptions with try, except and finally

45 min read Exception Handling

This is a free course. Log in to run the code exercises and track your progress.

Handling Exceptions with try, except and finally

An exception is an error raised while the program runs. If nothing handles it, the program stops with a traceback. To handle it, put the risky statements in a try block and the recovery in an except block.

try:
    a = int(input())
    b = int(input())
    result = a / b
except ZeroDivisionError:
    print("Denominator cannot be zero")
except ValueError:
    print("Please enter whole numbers")
else:
    print("Result:", result)   # only when no exception occurred
finally:
    print("Done")               # always runs
  • Python tries each except clause in order and runs the first one that matches the exception's type.
  • The else block runs only if the try block raised nothing.
  • The finally block runs in every case, exception or not. It is the place to close a file or release a resource.
  • A bare except: catches everything. Use it sparingly, because it also hides mistakes you would want to see.
Python exercise

Read lines until the line END. Add up the lines that are whole numbers, and count the lines that are not (catch the ValueError from int()). Print Sum: ... and Invalid: ....

total = 0
invalid = 0
while True:
    line = input()
    if line == "END":
        break
    total += int(line)  # wrap this in try / except ValueError
print("Sum:", total)
print("Invalid:", invalid)

Log in to edit and run this code.