OO Programming and Data Structures | CS 241

09 Teach : Team Activity - Exceptions

Overview

Practice raising and catching errors.

Instructions

We will create a class for a checking account that tracks the current balance of an account and the number of checks available. It should have the following methods and properties:

CheckingAcount
balance : float
check_count : int
__init__(starting_balance, num_checks) : None
deposit(amount) : None
write_check(amount) : None
display() : None
apply_for_credit(amount) : None

We will create the following exception classes:

Then, we will also use the following built-in exception classes:

Core Requirements

Begin with a supplied main function that will allow the user to create an account and call the various functions associated with it:


def display_menu():
    """
    Displays the available commands.
    """
    print()
    print("Commands:")
    print("  quit - Quit")
    print("  new - Create new account")
    print("  display - Display account information")
    print("  deposit - Desposit money")
    print("  check - Write a check")


def main():
    """
    Used to test the CheckingAccount class.
    """
    acc = None
    command = ""

    while command != "quit":
        display_menu()
        command = input("Enter a command: ")

        if command == "new":
            balance = float(input("Starting balance: "))
            num_checks = int(input("Numbers of checks: "))

            acc = CheckingAccount(balance, num_checks)
        elif command == "display":
            acc.display()
        elif command == "deposit":
            amount = float(input("Amount: "))
            acc.deposit(amount)
        elif command == "check":
            amount = float(input("Amount: "))
            acc.write_check(amount)
        elif command == "credit":
            amount = float(input("Amount: "))
            acc.apply_for_credit(amount)


if __name__ == "__main__":
    main()

Then complete the following:

  1. Create a CheckingAccount class as defined above. It should be initialized to an initial balance and a number of checks as passed in to the __init__() function.

    The deposit method should increase the balance by the amount passed in. The write_check method should decrease the balance by the amount given and decrease the number of checks by 1.

    The display method should display the current balance and the number of checks.

    The apply_for_credit method can be left blank (i.e., "pass").

    Run the program, try each method, and verify that they work as expected.

  2. Create classes for the exceptions BalanceError and OutOfChecksError. They should each inherit from the Exception class, and should accept a message as a parameter to the __init__ function. This message should then be passed to the __init__ function of the super class.

    Add logic to the CheckingAccount __init__ function and to the write_check function to raise an appropriate BalanceError if the resulting balance would be negative.

    Also, add logic to the CheckingAccount write_check function to raise an OutOfChecksError if there are no more checks.

    Test your code to ensure that the exceptions are raised as expected.

  3. Handle the exceptions you raised above in main so that the program does not crash. If an BalanceError is caught, display the message. If an OutOfChecks error is caught. Ask the user if they would like to buy more checks. If so, add 25 checks and deduct $5.00 from the balance.

    Verify that the these exceptions are properly handled.

Stretch Challenges

After completing the above steps. Make sure that everyone on the entire team is to this point and understands the material. Then, if you have time, move onto the following stretch challenges.

  1. Raise a ValueError in deposit and write_check if the amount is negative. Raise a NotImplementedError in the apply_for_credit. Make sure to provide appropriate messages. Then, handle them in main. Verify that they work correctly.

  2. Change balance to a property (think getter / setter) and make sure exceptions are appropriately raised if an attempt is made to set the balance to a negative number.

  3. Add an overage amount as a member variable to the BalanceError class. Then, set this amount whenever a BalanceError is raised. When handling the error, inform the use of how far over the balance they would have gone.

Instructor's Solution

As a part of this team activity, you are expected to look over a solution from the instructor, to compare your approach to that one. One of the questions on the I-Learn submission will ask you to provide insights from this comparison.

Please DO NOT open the solution until you have worked through this activity as a team for the one hour period. At the end of the hour, if you are still struggling with some of the core requirements, you are welcome to view the instructor's solution and use it to help you complete your own code. Even if you use the instructor's code to help you, you are welcome to report that you finished the core requirements, if you code them up yourself.

After working with your team for the one hour activity, click here for the instructor's solution.

Submission

You do not need to submit your program (just make sure that everyone has a copy of it for their reference). Instead, answer the accompanying questions in the I-Learn quiz.