From 912644d84172d74c1e0a3b1da0ae7a57ca2c3572 Mon Sep 17 00:00:00 2001 From: Tobias Berger Date: Tue, 21 Sep 2021 10:42:04 +0200 Subject: [PATCH] Improve test_constructor, add custom error --- fraction.cpp | 4 ++-- fraction.hpp | 5 +++++ tst_fractiontest.cpp | 15 ++++++++++++--- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/fraction.cpp b/fraction.cpp index 21f79f0..2a6c09d 100644 --- a/fraction.cpp +++ b/fraction.cpp @@ -40,7 +40,7 @@ namespace FractionNS { 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_denominator = denominator; reduce(); @@ -62,7 +62,7 @@ namespace FractionNS { this->m_numerator = numerator / gcd; } 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); this->m_denominator = denominator / gcd; } diff --git a/fraction.hpp b/fraction.hpp index 43d8ba0..ac988c4 100644 --- a/fraction.hpp +++ b/fraction.hpp @@ -3,6 +3,11 @@ #include 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 { private: diff --git a/tst_fractiontest.cpp b/tst_fractiontest.cpp index 62c80e1..57fc24c 100644 --- a/tst_fractiontest.cpp +++ b/tst_fractiontest.cpp @@ -60,11 +60,20 @@ void FractionTest::test_constructor() { // Zero Fraction f6 = Fraction(0); - QCOMPARE(f6, 0); + QCOMPARE(f6.getNumerator(), 0); 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() {