Exception Handling - Example 3 - try, throw, catch


#include <iostream>
#include <string>
using namespace std;

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("Error:  denominator = 0");
	}
	~fraction() { cout << "fraction destructor called\n"; }
	friend ostream& operator<<(ostream& o, const fraction& f)
	{
		return (o << f.numer << '/' << f.denom);
	}
};

int main()
{
	int i1, i2;
	cout << "Enter two ints => ";
	cin >> i1 >> i2;
	if (cin.good())
	{
		try
		{
			fraction f(i1,i2);
			cout << f << endl;	// Should this line be in the try block?
		}
		catch (const char* errmsg)
		{
			cerr << errmsg << endl;	// Does the program have to terminate now?
		}
	}
	else cerr << "Bad input\n";
	cout << "*** End of Program ***\n";
	system("Pause");
	return 0;
}

Program Execution

First run:

Enter two ints => 3 4
fraction constructor called
3/4
fraction destructor called
*** End of Program ***

Second run


Enter two ints => 2 three
Bad input
*** End of Program ***

Third run


Enter two ints => 2 0
Fraction constructor called
Error: denominator = 0
*** End of Program ***

How is this program an improvement?

Is there a problem?