Practice Programs

Practice Programs can generally be solved with a short program that directly applies the programming principles presented in this chapter.

  1. A function that returns a special error code is often better implemented by throwing an exception instead. This way, the error code cannot be ignored or mistaken for valid data. The following class maintains an account balance.

    class Account
    {
    private:
       double balance;
    public:
       Account()
       {
            balance = 0;
       }
        Account(double initialDeposit)
       {
            balance = initialDeposit;
       }
    double getBalance()
       {
            return balance;
       }
       // returns new balance or −1 if error
       double deposit(double amount)
       {
            if (amount > 0)
                balance += amount;
            else
                 return −1; // Code indicating error
            return balance;
       }
       // returns new balance or −1 if invalid amount
       double withdraw(double amount)
       {
       if ((amount > balance) || (amount < 0))
             return −1; else
             balance −= amount;
       return balance;
       }
    };

    Rewrite the class so that it throws appropriate exceptions instead of returning −1 as an error code. Write test code that attempts to withdraw and deposit invalid amounts and catches the exceptions that are thrown.

  2. The Standard Template Library includes a class named exception that is the parent class for any exception thrown by an STL function. Therefore, any exception can be caught by this class. The following code sets up a try-catch block for STL exceptions:

    #include <iostream>
    #include <string>
    #include <exception>
    using namespace std;
    
    int main()
    {
        string s = "hello";
        try
        {
           cout << "No exception thrown." << endl;
        }
        catch (exception& e)
        {
           cout << "Exception caught: " <<
                e.what() << endl;
        }
        return 0;
    }

    Modify the code so that an exception is thrown in the try block. You could try accessing an invalid index in a string using the at member function.