appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Exceptions and error handling

Lesson 3 of 510 minIntermediate

Catch the errors you can handle, let the others fail loudly and raise your own.

An exception is how Python reports that something went wrong. If nobody catches it, the program stops and prints a traceback: read it from the bottom, where the error type and message are.

try:
    value = int(text)
except ValueError:
    value = 0
else:
    print("parsed", value)
finally:
    print("always runs")
  • except runs when that error happens.
  • else runs only if there was no error.
  • finally always runs. Use it for cleanup.

Good habits

  • Catch specific exceptions. A bare except: hides bugs and even catches Ctrl+C.
  • Keep the try block small, so you know which line failed.
  • Do not silence an error with pass unless you really mean it. At least log it.

Raising your own

class OutOfStock(Exception):
    pass

def buy(stock, n):
    if n > stock:
        raise OutOfStock(f"only {stock} left")
    return stock - n

try:
    buy(2, 5)
except OutOfStock as e:
    print("sorry:", e)

NotePython style prefers asking forgiveness over permission (EAFP): try the operation and handle the error, instead of checking every condition first.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. When does the else block of a try statement run?
2. Why avoid a bare except:?
3. Where is the error type shown in a traceback?

Key terms