Exceptions

Objectgeoriënteerd programmeren in Python

Alex Yarosh

Content Quality Analyst @ DataCamp

a = 1
a / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
ZeroDivisionError: deling door nul
a = [1,2,3]
a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a[5]
IndexError: lijstindex buiten bereik
a = 1
a + "Hallo"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    a + "Hallo"
TypeError: ongeldige operand types voor +: /
'int' en 'str'
a = 1
a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a + b
NameError: naam 'b' is niet gedefinieerd
Objectgeoriënteerd programmeren in Python

Exception afhandeling

  • Voorkom dat het programma stopt bij een exception
  • try - except - finally:
try:
  # Probeer wat code te draaien

except ExceptionNameHere: # Voer deze code uit als ExceptionNameHere optreedt
except AnotherExceptionHere: #<-- meerdere except-blokken # Voer deze code uit als AnotherExceptionHere optreedt ...
finally: #<-- optioneel # Voer deze code altijd uit
Objectgeoriënteerd programmeren in Python

Exceptions opwerpen

  • raise ExceptionNameHere('Foutmelding hier')
def make_list_of_ones(length):
    if length <= 0:
       raise ValueError("Ongeldige lengte!")  # <--- Stopt het programma en geeft een fout
    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("Ongeldige lengte!")
ValueError: Ongeldige lengte!
Objectgeoriënteerd programmeren in Python

Exceptions zijn klassen

  • standaard exceptions erven van BaseException of Exception
    BaseException
    +-- Exception
        +-- ArithmeticError                     # <--- 
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              # <---
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Objectgeoriënteerd programmeren in Python

Aangepaste exceptions

  • Erven van Exception of een subklasse
  • Meestal een lege klasse
class BalanceError(Exception): pass
class Customer:
   def __init__(self, name, balance):
    if balance < 0 :
       raise BalanceError("Balance moet positief zijn!")
    else:
       self.name, self.balance = name, balance

Objectgeoriënteerd programmeren in Python
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 moet positief zijn!")
BalanceError: Balance moet positief zijn!
  • Exception onderbrak de constructor → object niet aangemaakt
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Objectgeoriënteerd programmeren in Python

Aangepaste exceptions opvangen

try:
  cust = Customer("Larry Torres", -100)
except BalanceError:
  cust = Customer("Larry Torres", 0)
Objectgeoriënteerd programmeren in Python

Aan de slag!

Objectgeoriënteerd programmeren in Python

Preparing Video For Download...