Improve test_constructor, add custom error
This commit is contained in:
parent
854e87e616
commit
912644d841
3 changed files with 19 additions and 5 deletions
|
@ -40,7 +40,7 @@ namespace FractionNS {
|
||||||
|
|
||||||
Fraction::Fraction(int numerator, int denominator)
|
Fraction::Fraction(int numerator, int denominator)
|
||||||
{
|
{
|
||||||
if(denominator == 0) throw std::range_error("Tried to divide by 0.");
|
if(denominator == 0) throw divide_by_zero_error();
|
||||||
this->m_numerator = numerator;
|
this->m_numerator = numerator;
|
||||||
this->m_denominator = denominator;
|
this->m_denominator = denominator;
|
||||||
reduce();
|
reduce();
|
||||||
|
@ -62,7 +62,7 @@ namespace FractionNS {
|
||||||
this->m_numerator = numerator / gcd;
|
this->m_numerator = numerator / gcd;
|
||||||
}
|
}
|
||||||
void Fraction::setDenominator(int denominator) {
|
void Fraction::setDenominator(int denominator) {
|
||||||
if(denominator == 0) throw std::range_error("Tried to divide by 0.");
|
if(denominator == 0) throw divide_by_zero_error();
|
||||||
auto gcd = FractionNS::gcd(this->m_numerator, denominator);
|
auto gcd = FractionNS::gcd(this->m_numerator, denominator);
|
||||||
this->m_denominator = denominator / gcd;
|
this->m_denominator = denominator / gcd;
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,6 +3,11 @@
|
||||||
#include <QString>
|
#include <QString>
|
||||||
|
|
||||||
namespace FractionNS {
|
namespace FractionNS {
|
||||||
|
class divide_by_zero_error : public std::logic_error {
|
||||||
|
public:
|
||||||
|
divide_by_zero_error() : std::logic_error("tried to divide by zero") {};
|
||||||
|
};
|
||||||
|
|
||||||
class Fraction
|
class Fraction
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
|
|
|
@ -60,11 +60,20 @@ void FractionTest::test_constructor() {
|
||||||
|
|
||||||
// Zero
|
// Zero
|
||||||
Fraction f6 = Fraction(0);
|
Fraction f6 = Fraction(0);
|
||||||
QCOMPARE(f6, 0);
|
QCOMPARE(f6.getNumerator(), 0);
|
||||||
Fraction f7 = Fraction(0, 3);
|
Fraction f7 = Fraction(0, 3);
|
||||||
QCOMPARE(f7, 0);
|
QCOMPARE(f7.getNumerator(), 0);
|
||||||
|
|
||||||
QCOMPARE(f6, f7);
|
QCOMPARE(f6.getDenominator(), f7.getDenominator());
|
||||||
|
|
||||||
|
// Invalid zero fraction
|
||||||
|
bool threw_divide_by_zero_error = false;
|
||||||
|
try {
|
||||||
|
Fraction(2, 0);
|
||||||
|
} catch (const divide_by_zero_error&) {
|
||||||
|
threw_divide_by_zero_error = true;
|
||||||
|
}
|
||||||
|
QVERIFY(threw_divide_by_zero_error);
|
||||||
}
|
}
|
||||||
|
|
||||||
void FractionTest::test_display() {
|
void FractionTest::test_display() {
|
||||||
|
|
Reference in a new issue