Error Handling and OOP Refactor
Add edge cases and exception handling, and refactor our Budget Tracker into an object-oriented design.
We began this project by gathering requirements from a simulated client.
Our AI Copilot helped us quickly generate a functional core, and it worked flawlessly in our tests. The code accepted the income and logged expenses, just as we wanted. However, in the real-world, users aren’t always perfect. What happens when they make a mistake?
Let’s find out.
The widget below contains the code we just generated. Run it as instructed. When you see the prompt that says Enter your monthly income, type the words five hundred, instead of entering the number 500.
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
struct Expense {
string category;
double amount;
};
static double income = 0.0;
static vector<Expense> expenses;
void addIncome(const string& amount) {
// Risky if input is not numeric
income = stod(amount);
}
void addExpense(const string& category, const string& amount) {
Expense e{category, stod(amount)};
expenses.push_back(e);
}
void runCLI() {
cout << "Welcome to Budget Tracker!" << endl;
cout << "Enter your monthly income: ";
string incomeInput;
getline(cin, incomeInput);
addIncome(incomeInput); // crash if non-numeric entered!
}
int main() {
runCLI();
return 0;
}The app crashed, and the terminal is filled with this text: terminate called after throwing an instance of ‘std::invalid_argument’what(): stodAborted (core dumped).
What went wrong?
The AI-generated code expected a numeric value. It attempted to convert "five hundred" into a number using stod(). Since the text was not numeric, the program raised an invalid_argument exception and stopped running.
The AI’s goal was to generate a solution based on the most common and ideal scenario.
It is assumed that a user would always input a valid number because that’s what a Budget Tracker implies. This type of code is great for a rapid prototype, but it’s brittle. It lacks the defensive layers that make a professional application resilient.
This is a ...