5. Exceptions

  • In case of execution illegal operation,

  • In case of resource being unavailable for us - ex. no access rights / not enough memory / servers is unavailable.

5.1. Syntax Errors

>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
                ^
SyntaxError: invalid syntax

5.2. Key Errors

capitals = {"France": "Paris", "Germany":"Berlin", "Poland":"Warsaw", "Check-republic":"Praga"}
capitals["USA"]

KeyError: 'USA'

5.3. Attribute error

  • If operation not possible to be done

"Hello Wordl".append('!')

5.4. Indentation Error

def testfunc():
print('Hello ;)')
 print('My name is:')

File "<ipython-input-4-9cd3c6fb52a1>", line 3
 print('My name is:')
 ^
IndentationError: unexpected indent

5.5. ModuleNotFoundError

import not_existing_module

ModuleNotFoundError: No module named 'not_existing_module'

Table of exceptions hierarchy in Python.

5.6. IndexError

attendees = ['Kasia', 'Adam', 'Tomek']
attendees[6]

IndexError: list index out of range

5.7. Exception handling

for i in range(3, -3, -1):
 try:
     print('Try of division by {}'.format(i))
     3 / i
 except ZeroDivisionError:
     print('Skipping, illegal operation !!!')

 finally:
     print('End of handling')
Try of division by 3
End of handling
Try of division by 2
End of handling
Try of division by 1
End of handling
Try of division by 0
Skipping, illegal operation !!!
End of handling
Try of division by -1
End of handling
Try of division by -2
End of handling

5.8. Raising an exception

def generate_report(input_data, outputfile):
    raise NotImplementedError('Function development still in progress')

NotImplementedError: Function development still in progress

5.9. Exercises part 1

  1. You got list of attendees

  • attendees = [“Kasia”, “Adam”, “Tomek”]

  1. Handle the situation when

  • Element no. 5 is gathered,

  1. Handle situation when trying to access to capital of Italy

    • use capitals = {"France": "Paris", "Germany":"Berlin", "Poland":"Warsaw", "Check-republic":"Praga"}