Exception Handling:

  • To handle exceptions gracefully, we use something called exception handling with try and except blocks.
  • The main Python keywords for dealing with exceptions are try and except
    • First you try something in one indented code block, and if that throws an exception, you add some more code in the except code block to deal with that case.

KeyError Exception:

  • Example:
  • In the try part of the code, we can tell Python to attempt and retrieve the email address of the user except when thereโ€™s a KeyError.
  • Then print a statement saying that it cannot find the email address
python
1user0 = {
2    'username': 'hbulldog',
3    'first': 'harpua',
4    'last': 'bulldog',
5    }
6
7try:
8    email = user0['emailAddress']
9except KeyError:
10    print("Error finding emailAddress")
11
12print("This code executes!")
  • Output:
1Error finding emailAddress
2This code executes!
  • Note, to verify it works, outside the except log we can print , โ€œThis code Executes!โ€
  • Notice that the exception is nowhere to be seen

TypeError Exception:

  • Occurs when you try to, for example, add and integer and a string together.
python
1user0 = {
2    'username': 'hbulldog',
3    'first': 'harpua',
4    'last': 'bulldog',
5    }
6
7user0['emailAddress'] = "hbulldog@student.wcu.edu"
8
9try:
10    email = user0['emailAddress']
11    numberedEmailAddress = 1 + email
12except TypeError:
13    print("These two data types can't be added together! ")
14
15print("This code executes!")

Output:

1These two data types can't be added together!
2This code executes!
  • Note that line 11 executes because the try and except blocks handle the TypeError Exception.