What are Exceptions?

  • Exceptions are events that occur during your program’s execution that normally cause your program to stop executing.
  • It usually means that some error has been encountered and that your program simply does not know how to deal with it.
  • A protocol that provides coherent ways to respond to unusual events.

The Three Classes of Errors (or ā€œbugsā€):

  • Exceptions are a class of errors that occur while a program is running.
  • Python defines many different types of exceptions to reflect the wide variety of different errors that can occur.
  • There are three classes of errors:
    1. Syntax Errors: Occur when you violate the basic rules of the language, which the interpreter or compiler can detect and report when first processing the code
    2. Runtime Errors: Runtime errors (or exceptions) arise when a syntactically correct piece of code is provided with data that cannot be executed; you might try to open a file that doesn’t exist.
    3. Logical Errors: Involve code that is both syntactically correct and generates no runtime exceptions but which nonetheless computes the wrong answer due to an incorrect translation of an algorithm into computer code. These are the most insidious and difficult to track down.

What Does an Exception Look Like?

  • Using our previous dictionary, user0, if we try to access the user’s email address (which is not included in the dictionary), in the following way:
python
1user0 = {
2    'username': 'hbulldog',
3    'first': 'harpua',
4    'last': 'bulldog',
5    }
6
7email = user0['emailAddress']
  • Output: We see once the code gets is executed, we get the KeyError exception:
1email = user0['emailAddress']
2KeyError: 'emailAddress'