Error handling in C++, constructors vs. regular methods
Posted
by
Dennis Ritchie
on Stack Overflow
See other posts from Stack Overflow
or by Dennis Ritchie
Published on 2012-12-02T09:43:37Z
Indexed on
2012/12/02
11:04 UTC
Read the original article
Hit count: 241
c++
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?
© Stack Overflow or respective owner