Ausnahmen

Einführung in objektorientierte Programmierung in Python

George Boorman

Curriculum Manager, DataCamp

a = 1
a / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
a = [1,2,3]
a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a[5]
IndexError: list index out of range
a = 1
a + "Hello"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    a + "Hello"
TypeError: unsupported operand type(s) for +: /
'int' and 'str'
a = 1
a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a + b
NameError: name 'b' is not defined
Einführung in objektorientierte Programmierung in Python

Ausnahmen behandeln

  • Verhindern, dass das Programm bei einer Ausnahme beendet wird
  • try - except - finally:
try:
    print(5 + "a")

except TypeError: print("Du kannst keine ganze Zahl zu einem String addieren, aber du kannst sie multiplizieren!")
# Mehrere except-Blöcke möglich except AnotherExceptionHere: # Dies ausführen, wenn AnotherExceptionHere passiert
# Optionaler finally-Block finally: print(5 * "a")
Einführung in objektorientierte Programmierung in Python

Ausgabe der Fehlerbehandlung

Du kannst keine ganze Zahl zu einem String addieren, aber du kannst sie multiplizieren!
aaaaa
Einführung in objektorientierte Programmierung in Python

Ausnahmen auslösen

def make_list_of_ones(length):
    if length <= 0:
        # Eigene Meldung, wenn ValueError auftritt
        # Beendet das Programm und wirft den Fehler
       raise ValueError("Invalid length!")
    return [1]*length

make_list_of_ones(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    make_list_of_ones(-1)
  File "<stdin>", line 3, in make_list_of_ones
    raise ValueError("Invalid length!")
ValueError: Invalid length!
Einführung in objektorientierte Programmierung in Python

Ausnahmen sind Klassen

  • Ausnahmen erben von BaseException oder Exception
    BaseException
    +-- Exception
        +-- ArithmeticError                     
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Einführung in objektorientierte Programmierung in Python

Eigene Ausnahmen

  • Von Exception oder einer Unterklasse erben
  • Meist eine leere Klasse
class BalanceError(Exception): 
    pass

class Customer: def __init__(self, name, balance): if balance < 0 : raise BalanceError("Balance has to be non-negative!") else: self.name = name self.balance = balance
Einführung in objektorientierte Programmierung in Python

Exception im Konstruktor

cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    cust = Customer("Larry Torres", -100)
  File "script.py", line 6, in __init__
    raise BalanceError("Balance has to be non-negative!")
BalanceError: Balance has to be non-negative!
Einführung in objektorientierte Programmierung in Python

Ausnahmen beenden das Programm

  • Exception hat den Konstruktor unterbrochen → Objekt nicht erstellt
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Einführung in objektorientierte Programmierung in Python

Eigene Ausnahmen abfangen

try:
    cust = Customer("Larry Torres", -100)
except BalanceError:
    cust = Customer("Larry Torres", 0)
Einführung in objektorientierte Programmierung in Python

Lass uns üben!

Einführung in objektorientierte Programmierung in Python

Preparing Video For Download...