Error handling in C++, constructors vs. regular methods
- by Dennis Ritchie
I have a cheesesales.txt CSV file with all of my recent cheese sales. I want to create a class CheeseSales that can do things like these:
CheeseSales sales("cheesesales.txt"); //has no default constructor
cout << sales.totalSales() << endl;
sales.outputPieChart("piechart.pdf");
The above code assumes that no failures will happen. In reality, failures will take place. In this case, two kinds of failures could occur:
Failure in the constructor: The file may not exist, may not have read-permissions, contain invalid/unparsable data, etc.
Failure in the regular method: The file may already exist, there may not be write access, too little sales data available to create a pie chart, etc.
My question is simply: How would you design this code to handle failures?
One idea: Return a bool from the regular method indicating failure. Not sure how to deal with the constructor.
How would seasoned C++ coders do these kinds of things?