C++ PROGRAMMING: PLEASE MAKE SURE THE PROGRAM COMPILES AND RUNS FOR 5 STARS :-)
ID: 3806254 • Letter: C
Question
C++ PROGRAMMING: PLEASE MAKE SURE THE PROGRAM COMPILES AND RUNS FOR 5 STARS :-)
HERE IS THE CODE TO EDIT BELOW (PLEASE ONLY ADD CODE):
objectives: 1. Handling exceptions within a pro 2. Using trylcatch block 3. Creating exception class Question: Design a program that repeatedly asks for the dimensions (length and width of a rectangle and computes the area. Consider a class Rectangle which includes the following two functions: void Rectangle setWidth (int width) void Rectangle setLength (int length) If the length and width are positive, then above functions store the values in the Rectangle object. However, if the length and width are negative, the functions throw an object of Dim.Error class that includes a message indicating which method was called and the reason for the error. Note: DimError class is used by the Rectangle class for showing error messages.Explanation / Answer
//Modification to code as per requirement
#include<iostream>
#include<string>
using namespace std;
class DimError
{
private:
string message;
public:
//implement the methods
DimError(string a) //constructor sets exception message to message
{
message=a;
}
string what() //return message
{
return message;
}
};
class Rectangle
{
private:
int length, width;
public:
//implement the methods
void setLength(int len)// throws DimError
{
if(len>=0)
length=len;
else //thows the object of DimError with error message
throw DimError("Length could not be negative ");
}
void setWidth(int wid)
{
if(wid>=0)
width=wid;
else
throw DimError("width could not be negative ");
}
int area() //returns area of rectangle
{
return length*width;
}
};
int main(void)
{
Rectangle r;
try
{
while (true)
{
int l, w;
cout << "Enter a length: ";
cin >> l;
cout << "Enter a width: ";
cin >> w;
r.setLength(l);
r.setWidth(w);
cout << "The area is: " << r.area() << endl;
}
}
catch (DimError de)
{
cout << "Couldn't set the rectangle's dimensions: " << endl<< de.what() << endl;
}
cout << "Exiting..." << endl;
return 0;
}
/*
Output :
Enter a length: 12
Enter a width: 123
The area is: 1476
Enter a length: -21
Enter a width: 12
Couldn't set the rectangle's dimensions:
Length could not be negative
Exiting...
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.