Errors & Exceptions

Syntax Errors

>>> print(invalid code)
  File "<stdin>", line 1
    print(invalid again)
                      ^
SyntaxError: invalid syntax

>>> while True
  File "<stdin>", line 1
    while True
             ^
SyntaxError: invalid syntax
  • Syntax Errors occur during code parsing.
  • The parser show us where exactly the errors is (line X and ^ pointer)

Exceptions

>>> print(invalid)
>>> [x / x for x in range(10)]
>>> del 'I am a string!'[0]
>>> print(invalid)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'invalid' is not defined

>>> del 'I am a string'[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

>>> [x/x for x in range(10)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
ZeroDivisionError: division by zero

What is going to happen?

Exceptions

  • Syntactically correct statements may cause Exceptions. 
  • They occur while Python tries to interpret your code

Exceptions Message Structure

  • Type -> TypeError, KeyError, ZeroDevisionError
  • Description -> 'str' object doesn't support item deletion
  • Where it happened -> File "<stdin>", line 1
  • Traceback
 

Catching Exceptions

while True:
    try:
        age = int(input('Enter your age: '))
        print(age)
    except ValueError:
        print('Invalid input')
        break
Enter your age: 10
10
Enter your age: 20
20
Enter your age: Marto
Invalid input

The try/except block

try:
    pass  # tries to execute the code here
except Exception:
    pass  # catches the exception from the try block
else:
    pass  # runs after ONLY IF try block succeeds
finally:
    pass  # executes after everything!

The try/except block

print('You have 10 inputs')
counter = 0
ages = []

while counter <= 10:
    try:
        age = int(input('Enter your age: '))
    except ValueError:
        print('Invalid input')
    else:
        ages.append(age)
    finally:
        counter += 1
  1. We try to parse the input
  2. If it's not valid we show a message to the user
  3. If it's valid we update the list
  4. We make sure the counter is correct whatever happens

In the except clause

You can catch a specific error

person = {age: 23, name: 'Gosho'}

try:
  job = person['job']
except KeyError:
  print('''We found a person with no job.
        Please, help him.''')

You can catch all errors

person = {age: 23, name: 'Gosho'}

try:
  job = person['job']
  new_age = person['age'] / 0
except Exception as e:
  print('''Something went wrong.
        The error was: {}'''.format(e))

using the base exception class

You can act differently to different errors

person = {age: 23, name: 'Gosho'}

try:
  job = person['job']
  new_age = person['age'] / 0
except KeyError:
  print('There is no job.')
except ZeroDivisionError:
  print('You cannot divide by 0')

using more than one exception class

You can catch more than one exception at once

person = {age: 23, name: 'Gosho'}

try:
  job = person['job']
  new_age = person['age'] / 0
except (KeyError, ZeroDivisionError) as err:
  print(f'Something is wrong with the person: {err}')

Raising Errors

try:
  x = '10' / 0
except Exception:
  raise TypeError('Marto is testing')
  
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
TypeError: Marto is testing

Python 101 9th Exceptions

By Hack Bulgaria

Python 101 9th Exceptions

  • 911