Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

plesas i wnat help. how i can use Try and Catch with this code. #ifndef Payroll_

ID: 3690551 • Letter: P

Question

plesas i wnat help. how i can use Try and Catch with this code.

#ifndef Payroll_hpp

#define Payroll_hpp

#include <stdio.h>

class Payroll {

private:

double hoursWorked;

double payRate;

double gross;

public:

Payroll();

Payroll(double , double);

void setHoursWorked(double);

void setPayRate(double);

double getHoursWorked();

double getPayRate();

double getGrossPay();

};

#endif

#include "Payroll.hpp"

Payroll::Payroll()

{

}

Payroll::Payroll(double payRate, double hoursWorked)

{

payRate=payRate;

hoursWorked=hoursWorked;

gross=hoursWorked*payRate;

}

double Payroll::getHoursWorked()

{

return hoursWorked;

}

double Payroll::getPayRate()

{

return payRate;

}

void Payroll::setHoursWorked(double hours)

{

hoursWorked=hours;

}

void Payroll::setPayRate(double pay)

{

payRate=pay;

}

double Payroll::getGrossPay()

{

return gross =hoursWorked * payRate;

}

#include <iostream>

#include <iomanip>

#include "Payroll.hpp"

using namespace std;

int main()

{

Payroll employee;

double pay;

double hours;

cout << "Enter the employee's rate of pay per hour: ";

cin >> pay;

cout << "Enter the employee's hours worked for the week: ";

cin >> hours;

employee.setPayRate(pay);

employee.setHoursWorked(hours);

cout<<"The employee's hours worked is: "<<employee.getHoursWorked()<<endl;

cout<<"The employee's pay rate is: "<<employee.getPayRate()<<endl;

cout << "The gross pay for employee is: " <<employee.getGrossPay()<< endl;

return 0;

}

Explanation / Answer

You can add try catch block for input validation.


#include <iostream>

#include <iomanip>

#include "Payroll.hpp"

using namespace std;

int main()

{

   Payroll employee;

   double pay;

   double hours;

   try {
            cout << "Enter the employee's rate of pay per hour: ";
           cin >> pay;
            if (cin.fail())
                throw "Sorry, I don't think that's a number?";
            if (pay < 0)
                throw "Sorry, no negative numbers.";
              
            cout << "Enter the employee's hours worked for the week: ";
           cin >> hours;
           if (cin.fail())
                throw "Sorry, I don't think that's a number?";
            if (hours < 0)
                throw "Sorry, no negative numbers.";
            cin.clear();
        }
        catch (char* error) {
            cout << error<<endl;
        }

   employee.setPayRate(pay);

   employee.setHoursWorked(hours);

   cout<<"The employee's hours worked is: "<<employee.getHoursWorked()<<endl;

   cout<<"The employee's pay rate is: "<<employee.getPayRate()<<endl;

   cout << "The gross pay for employee is: " <<employee.getGrossPay()<< endl;

   return 0;

}