I searched for SO to answer this question, but did not find it.
When an object throws an exception at the end of the constructor, is the object valid or does one of them “depend on the construction technique”?
Example:
struct Fraction
{
int m_numerator;
int m_denominator;
Fraction (double value,
int denominator);
};
Fraction::Fraction(double value, int denominator)
: m_numerator(0), m_denominator(denominator)
{
if (denominator == 0)
{
throw std::logic_error("Denominator is zero.");
}
m_numerator = static_cast<int>(value * static_cast<double>(denominator));
double actual_value = 0.0;
actual_value = static_cast<double>(m_numerator) / static_cast<double>(m_denominator);
double error = fabs(actual_value - value);
if (error > 5.0E-5)
{
throw std::logic_error("Can't represent value in exact fraction with given denominator");
}
}
Program:
int main(void)
{
try
{
Fraction f1(3.14159264, 4);
}
catch (...)
{
cerr << "Fraction f1 not exactly representable as fraction with denom. of 4.\n";
}
return EXIT_SUCCESS;
}
In this example, can f1 be used after the exception is caught knowing that this is an approximate value?
Data items have been created and initialized.
I do not see any C ++ language rule that is violated above.
Edit: Changed error delta value from 5.0E05 to 5.0E-5.
source
share