OO Programming and Data Structures | CS 241

09 Prepare : Reading

Outcomes

At the end of this week, successful students will be able to:

  1. Show fluency in discussing exceptions and error handling.

  2. Write programs that correctly use exceptions and error handling to solve problems.

Preparation Material

For this week, please read the following introduction to Exception/Error handling:

A note about one of the examples in the reading:

For one of the examples in the reading, they showed how to use a while True loop with a break statement. While this works, it can sometimes make the code difficult to follow to have loops exit at non-standard times (i.e., using break statements), so it is usually considered better practice to let the loop's condition cause it to exit.

With this in mind, we could rework the code from the example to be something more like:


valid_input = False

while not valid_input:
    try:
        n = int(input("Please enter an integer: "))
        valid_input = True
    except ValueError:
        print("Not a valid integer, please try again.")

print("Successfully entered an integer.")

Creating Custom Types of Errors

In addition to using the built-in types, we can also define our own custom types of errors. See the official Python documentation for an example of how to do this, but in short, assuming we wanted to create an exception class for a InvalidStudentError, the Python code would look as follows:


class InvalidStudentError(Exception):
    def __init__(self, message):
        # Don't forget to pass the message to the base class
        super().__init__(message)

Then we could use our new InvalidStudentError, just like any other error:

if student.name == None:
    raise InvalidStudentError("The student must have a name")