PyPython
IntermediateLesson 8 of 12

Error Handling – Python

try/except, custom errors and cleaning up with finally.

Errors (exceptions) terminate the program – unless you catch them with try/except.

try:
    zahl = int("abc")
except ValueError as e:
    print("Invalid number:", e)
else:
    print("All ok:", zahl)
finally:
    print("Always runs")

With raise you trigger errors yourself, and with a custom class you make them meaningful:

class KontoFehler(Exception):
    pass

def abheben(saldo, betrag):
    if betrag > saldo:
        raise KontoFehler("Insufficient balance")
    return saldo - betrag

try:
    abheben(50, 100)
except KontoFehler as e:
    print("Error:", e)
WarningNever use a blanket except: without a type – you would also swallow typos and Ctrl+C. Name the specific exception.