// File: eh8a.cpp - Exception Handling classes
#include <<ostream>
#include <string>
using namespace std;
class ZeroDenominator
{
public:
ZeroDenominator() {}
friend ostream& operator<<(ostream& out, const ZeroDenominator& error);
};
class fraction
{
int numer, denom;
public:
fraction(int n = 0, int d = 1) : numer(n), denom(d)
{
cout << "fraction constructor called\n";
if (denom == 0) throw ZeroDenominator();
}
~fraction() { cout << "fraction destructor called\n"; }
friend ostream& operator<<(ostream& o, const fraction& f)
{
return (o << f.numer << '/' << f.denom);
}
};
class InputError
{
string stream;
public:
InputError(string name) : stream(name) {}
friend ostream& operator<<(ostream& out, const InputError& error);
};
ostream& operator<<(ostream& out, const InputError& error)
{
out << "Error in " << error.stream << endl;
return out;
}
ostream& operator<<(ostream& out, const ZeroDenominator& error)
{
out << "ZeroDenominator Error" << endl;
return out;
}
int main()
{
int i1, i2;
cout << "Enter two ints => ";
try {
cin >> i1 >> i2;
if (cin.fail()) throw InputError("cin");
// You could also use (!cin) instead of (cin.fail())
// cin.bad() did not detect error in cin
fraction f(i1,i2);
cout << f << endl; // Should this line be in the try block?
}
catch (const InputError& error) {
cerr << error << endl;
}
catch (const ZeroDenominator& errmsg) {
cerr << errmsg << endl;
}
catch (...) {
cerr << "help\n";
}
cout << "*** End of Program ***\n";
return 0;
}
***** Compilation and Execution using gnu 3.4.2 on Windows XP *****
C:\deanza\cis52g\examples\exception_handling>g++ eh8a.cpp -Wall -fexceptions C:\deanza\cis52g\examples\exception_handling>a Enter two ints => 3 4 fraction constructor called 3/4 fraction destructor called *** End of Program *** C:\deanza\cis52g\examples\exception_handling>a Enter two ints => 3 0 fraction constructor called ZeroDenominator Error *** End of Program *** C:\deanza\cis52g\examples\exception_handling>a Enter two ints => one two Error in cin *** End of Program ***