Question
getting an error within my code fro c++ and cannot figure out how to resolve. what I am trying to do is Use exceptions so
getting an error within my code fro c++ and cannot figure out how to resolve. what I am trying to do is Use exceptions so that your program handles the exceptions division by zero and invalid input.
codes are the following;
fractiontype.h
#pragma once #ifndef FRACTIONTYPE_H #define FRACTIONTYPE_H #include
using namespace std;
//the class for fractions which is dervied from the exception class class fractionException : public exception { private: const char *msg; public: fractionException(const char *m) :msg(m) {} virtual const char *what() const throw() { return msg; } };
//this is the class defintion for fraction class fractionType { private: int n; int d; public: fractionType() : n(0), d(1) {} fractionType(int num, int den) : n(num), d(den) { if (den == 0) throw fractionException("Division by zero");//this gives the zero exception }
fractionType operator/(const fractionType &x); friend ostream & operator<< (ostream &out, const fractionType &f); friend istream& operator>>(istream &in, fractionType &f); }; #endif //End Fraction Header
MainProgram.cpp
#include
int main() { try {
fractionType
fractionType
fractionType
cout << fixed;
cout << showpoint;
cout << setprecision(2);
num3 = num1 / num2;
cout << num1 << " / " << num2 << " = " << num3 << endl;
}
catch (fractionException e) {
cout << "Exception caight in main: " << e.what() << endl;
} system("pause"); return 0; } //main end
FractionType.cpp
#include "fractionType.h" int main() { std::ostream& operator<<(std::ostream &os, fractionType const & frac) { return os << "frac( " << frac.n << " / " << frac.d << " )"; }
std::istream &operator>>(std::istream & is, fractionType & frac) { is >> frac.n; is >> frac.d; return is; }
fractionType operator/(fractionType const &a, fractionType const &b) { if (a.d == 0 || b.d == 0) throw fractionException("Division by zero"); return fractionType{ (a.n * b.n) / (a.d * b.d) }; }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started