← CS Lab Programming Foundations / Python Error Handling
Python Error Handling — card 1 of 4
Python Error Handling — card 2 of 4
Python Error Handling — card 3 of 4
Python Error Handling — card 4 of 4

Exceptions let your code say "this went wrong" without crashing the whole program. Instead of checking every possible failure up front, you attempt the work and deal with trouble only if it actually shows up.

Where you meet it

What it does

An exception is a signal that travels upward. When code raises one, Python stops the current line and looks for a matching except handler up the call stack. If one is found, control jumps there; if none is, the program stops and prints a traceback.

A bare except: doesn't make errors go away — it hides the bugs that bite you later, Ctrl+C included.

How it works

The Pythonic style is EAFP — "easier to ask forgiveness than permission": just try the thing, then catch the specific failure.

try:
    n = int(user_input)          # risky line
except ValueError as err:        # catch this exact failure
    print("not a number:", err)  # err holds the message
else:
    print("parsed", n)           # runs only if no error
finally:
    log("attempt finished")      # always runs, error or not

Bind the object with as err to read its message. Raise your own with raise PaymentError("declined"). When re-raising inside a handler, chain the cause so the original is preserved:

except OSError as e:
    raise ConfigError("bad config") from e

Watch out

  • Never write a bare except:. It also swallows KeyboardInterrupt and SystemExit — which inherit from BaseException, not Exception — so Ctrl+C stops working. Catch specific types, or except Exception at most.
  • Don't silently swallow errors. An empty except: pass hides real bugs; at minimum log it, or let it propagate.
  • For cleanup, prefer with. A context manager (with open(...) as f:) closes the resource for you — cleaner than a hand-written finally.

Go deeper

Exceptions lassen deinen Code "hier ging etwas schief" sagen, ohne das ganze Programm abstürzen zu lassen. Statt jeden möglichen Fehler vorher abzuprüfen, versuchst du die Aktion und kümmerst dich nur dann um Probleme, wenn sie wirklich auftreten.

Wo es vorkommt

Was es tut

Eine Exception ist ein Signal, das nach oben wandert. Wird eine geworfen, stoppt Python die aktuelle Zeile und sucht im Aufrufstapel nach einem passenden except-Handler. Findet sich einer, springt die Ausführung dorthin; findet sich keiner, hält das Programm an und gibt einen Traceback aus.

Ein nacktes except: lässt Fehler nicht verschwinden — es versteckt die Bugs, die dich später beißen, Strg+C inklusive.

Wie es funktioniert

Der pythonische Stil ist EAFP — "easier to ask forgiveness than permission": einfach versuchen und den konkreten Fehler gezielt abfangen.

try:
    n = int(user_input)          # riskante Zeile
except ValueError as err:        # genau diesen Fehler fangen
    print("keine Zahl:", err)    # err enthält die Meldung
else:
    print("geparst", n)          # läuft nur ohne Fehler
finally:
    log("Versuch beendet")       # läuft immer, Fehler oder nicht

Mit as err bindest du das Objekt und liest seine Meldung. Eigene Fehler wirfst du mit raise PaymentError("declined"). Beim Weiterwerfen in einem Handler die Ursache verketten, damit das Original erhalten bleibt:

except OSError as e:
    raise ConfigError("bad config") from e

Worauf achten

  • Nie ein nacktes except: schreiben. Es schluckt auch KeyboardInterrupt und SystemExit — die von BaseException erben, nicht von Exception — und Strg+C funktioniert dann nicht mehr. Fang gezielte Typen ab, höchstens except Exception.
  • Fehler nicht still schlucken. Ein leeres except: pass verbirgt echte Bugs; mindestens loggen oder weiterreichen lassen.
  • Zum Aufräumen besser with. Ein Kontextmanager (with open(...) as f:) schließt die Ressource selbst — sauberer als ein handgeschriebenes finally.

Mehr dazu

Next up
Programming FoundationsPython Environments & Packaging Programming FoundationsPython Web Frameworks All concepts →