Error Handling and OOP Refactor
Explore how to enhance a basic Budget Tracker by implementing error handling with try-catch blocks and input validation. Learn to transform procedural code into an object-oriented design by creating a BudgetTracker class with private fields and member functions, resulting in a robust and user-friendly C++ application.
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 ...