Objectives: 1. Handling exceptions within a program 2. Using try/catch block 3.
ID: 3733421 • Letter: O
Question
Objectives: 1. Handling exceptions within a program 2. Using try/catch block 3. Creating exception class in C++ programming with visual studio.
Lab 16.app:
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 DimError 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. Download lab16.cpp to get the driver function. Submit one single cpp file named as lastname firstname labl6.cpp CAWINDOWSlsystem321cmd.exe Enter a length: 6 Enter a width: 3 The area is: 18 Enter a length: 12 Enter a width: -3 Couldn't set the rectangle's dimensions: setWidth called with a negative width. Exiting... Press any key to continue..-Explanation / Answer
#include <iostream>
using namespace std;
class DimError {
private:
string message;
public:
//implement the methods
DimError(string s){
message = s;
}
string what() {
return message;
}
};
class Rectangle {
private:
int length, width;
public:
//implement the methods
Rectangle() {
}
void setLength(int l){
if(l < 0){
throw DimError("couldnt find area setlength called with negative length");
}
else{
length = l;
}
}
void setWidth(int w){
if(w < 0){
throw DimError("couldnt find area setwidth called with negative width");
}
else{
width = w;
}
}
int area() {
return width * length;
}
};
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:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter a length: 6
Enter a width: 3
The area is: 18
Enter a length: 22
Enter a width: -4
Couldn't set the rectangle's dimensions:
couldnt find area setwidth called with negative width
Exiting...
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.