Exception Handlers

I am trying to grasp a better understanding of exception handlers. I have a program that is taking some information from a user with a selection of 1 or 2, I want the program to throw an exception if the user enters anything other than 1 or 2. The code I have throws the exception no matter what entry they have. Is there something that I am missing here?

driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "employee.h"

using namespace std;

// printCheck function
// Purpose: Create a paystub for an employee
// Parameters: Employee information
// Returns: void
void printCheck(const Employee&);

//Setting variables
int userSelection;
string fileName;

//main method
//Purpose: To call to my employee functions and display information about employees
//Parameters: None
//Returns: None
int main()
{
	//Getting information from the user
	cout << "This program has two options:" << endl;
	cout << "1 - Create a data file, or " << endl;
	cout << "2 - Read data from a file and print paychecks." << endl;
		try
		{
			cout << "Please enter <1> to create a file or <2> to print checks: ";
			cin >> userSelection;
			if (userSelection != 1 || userSelection != 2)
			{
				throw "Invalid Input! Program will now close.";
			}
		}
		catch (const char* Message)
		{
			cout << "\nError: " << Message << endl;
			system ("Pause");
			return 0;
		}
		cout << endl;
		try
		{
			cout << "Please enter file name: ";
			cin >> fileName;
			if (fileName != fileName)
				throw "No such file exists.";
		}
		catch (const char* Message)
		{
			cout << "\nError: " << Message << endl;
			system("Pause");
			return 0;
		}
		cout << endl;

	Employee b1(1234, "Bruce Banner", "436 E 900 S", "801-465-2291", 10.00, 45);
	Employee b2(1569, "Tony Stark", "7000 E 9680 S", "801-941-0745", 12.50, 30);
	Employee b3(1967, "Charles Xavier", "500 W 780 N", "801-754-3687", 15.00, 40);

	//If statement that handles the writeEmployee information
	if (userSelection == 1)
	{
		ofstream odataFile(fileName);
		if (odataFile.good())
		{
			//Write the data
			b1.writeEmployee(odataFile);
			b2.writeEmployee(odataFile);
			b3.writeEmployee(odataFile);
			odataFile.close();
			cout << "Data file created ... you can now run option 2." << endl;
			system("PAUSE");
		}
	}
	//If statment that handles the readEmployee information
	if (userSelection == 2)
	{
		ifstream idataFile(fileName);
		if (idataFile.good())
		{
			// Read the file
			if (b1.readEmployee(idataFile))
			{
				// If read was successful, print b1
				printCheck(b1);
			}
			if (b2.readEmployee(idataFile))
			{
				//If read was successful, print b2
				printCheck(b2);
			}
			if (b3.readEmployee(idataFile))
			{
				//If read was successful, print b3
				printCheck(b3);
			}
			else // the read operation failed ... display a message
				cout << "\nRead failed";
		}
	}
}

void printCheck(const Employee& b)
{
	cout << "\n--------------------Marvel Comics--------------------" << endl;
	cout << "\n\nPay to the order of " << b.getEmployeeName() << ".............$" << setprecision(2) << fixed << b.getCalcPay() << endl;
	cout << "\n\nS.H.I.E.L.D Bank" << endl;
	cout << "-----------------------------------------------------" << endl;
	cout << "Hours worked: " << b.getWeeklyHours() << endl;
	cout << "Hourly Wage: " << b.getHourlyWage() << endl;
	cout << "\n" << endl;
	system("PAUSE");
	system("CLS");
}


employee.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <stdexcept>
#include <exception>

using namespace std;

//Provides start point for employee information
class Employee
{
private:
	//Setting initial values
	int employeeNumber;
	string employeeName;
	string employeeAddress;
	string phoneNumber;
	double hourlyWage;
	double weeklyHours;
	double calcPay;

public:
	//Default constructor
	//Purpose: Initialize data in employee object to null
	//Parameters: None
	//Returns: None
	Employee( );

	//Parameterized constructor
	//Purpose: Initialize data in employee object to specified data
	//Parameters: Employee number, name, address, phone number, hourly wage, week hours
	//Returns: None
	Employee(int, string, string, string, double, double);

	//readEmployee function
	//Purpose: Reads employee information from a file
	//Parameters: A reference from the ifstream object
	//Returns: True if read is successful
	bool readEmployee(ifstream&);

	//writeEmployee function
	//Purpose: Writes employee information to a file
	//Parameters: A reference from the ofstream object
	//Returns: None
	void writeEmployee(ofstream&);

	// getEmployeeNumber function
	// Purpose: returns number of employee
	// Parameters: none
	// Returns: The employees number
	int getEmployeeNumber( ) const;

	// getName function
	// Purpose: Returns name of employee
	// Parameters: none
	// Returns: The employees name
	string getEmployeeName( ) const;

	// getAddress function
	// Purpose: Returns address of employee
	// Parameters: none
	// Returns: The employees address
	string getEmployeeAddress( ) const;

	// getPhoneNumber function
	// Purpose: Returns phone number of employee
	// Parameters: none
	// Returns: The employees phone number
	string getPhoneNumber( ) const;

	// getHourlyWage function
	// Purpose: Returns hourly wage of employee
	// Parameters: none
	// Returns: The employees wage
	double getHourlyWage( ) const;

	// getWeeklyHours function
	// Purpose: Returns weekly hours of employee
	// Parameters: none
	// Returns: The employees weekly hours
	double getWeeklyHours( ) const;

	// getCalcPay function
	// Purpose: Returns total pay for the employee
	// Parameters: none
	// Returns: The employees paycheck
	double getCalcPay( ) const;
};
Line 29: Your if statement is faulty. If user enters 1, userSelection != 2 will be true and the exception will be thrown. You want an && condition, not an || condition.
Oh wow, thanks AbstractionAnon that was a lot easier than I had thought
I also have a question on lines 41-54 of my driver. It is not catching the exception that I have placed. I am attempting to catch the exception when the inputted file name isn't available. So if the user enters a file name of "Data" and comes back and enters "Datas" it will stop them and ask for another try.
You're not having much luck with if statements. :)

Again, your if statement is faulty.
 
    if (fileName != fileName)

You have the same variable on both sides of the != operator.
The same variable will never be not equal to itself.
That's true! what is a good way to check if it has been created?
Try and open it.
I am trying something like this and it isn't working.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
		try
		{
			cout << "Please enter file name: ";
			cin >> fileName;
			ifstream idataFile(fileName);
			if (idataFile.bad())
			{
				throw "No such file exists.";
			}
		}
		catch (const char* Message)
		{
			cout << Message << "\nTry again (Press 0 to exit) " << endl;
			system("Pause");
		}
		cout << endl;
I'm guessing that you mean it is not detecting that the file doesn't exist.

bad() detects only "Read/writing error on i/o operation".
if (! good()) and if (bad()) are not the same thing. Seems contradictory, but that's the way it is. In the case of the file not being found, the fail bit is set. That is not tested by bad().
See the following truth table: http://www.cplusplus.com/reference/ios/ios/bad/

You say you're trying to get a better grasp on exception handling. That's great. I do have some concerns with your code, though. If you throw the exception at line 8, your catch handler will get control, but your catch handler says "try again" and falls through to line 16, continuing with your program (original line 56). There is no transfer of control back to your input statement at line 4. Also, the code to handle "press 0 to exit" isn't implmented.

Last edited on
I do have it processing in a loop, I just included the snip of the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
		while (true)
		{
			try
			{
				cout << "Please enter file name: ";
				cin >> fileName;
				ifstream idataFile(fileName);
				if (idataFile.bad())
				{
					throw "No such file exists.";
				}
			}
			catch (const char* Message)
			{
				cout << Message << "\nTry again (Press 0 to exit): " << endl;
				cin >> retry;
				if (retry == 0)
				{
					break;
					return 0;
				}
			}
			cout << endl;
		}
Still have a couple of concerns:

Line 11: You need a break statement after line 11. If the file is found, you don't want to continue forever prompting for the file name.

Line 19: You probably don;t want the break statement here. You will never reach the return statement which is what I assume you want to execute to take you out of the program (main).
Very helpful! thank you for showing me my errors. I am quite new to C++ and it's a great language, just a little rough for me to learn the differences. Thanks again AbstractionAnon.
Topic archived. No new replies allowed.