How to Handle Incorrect Values in a Constructor?
Last Updated :
12 Feb, 2024
In C++, constructors are used to construct and initialize the object of its class. If incorrect values are given to the constructor, then it may cause inconsistency in a program. In this article, we will learn how to handle incorrect values in a constructor in C++
Handling Incorrect Arguments for Constructor in C++
In C++, the most common method is to handle the incorrect values that are passed to the constructor as the arguments is to throw a std::invalid_argument exception if the arguments are not as desired and catch that exception in the code where the object is being constructed.
C++ Program to Handle Incorrect Values in Constructor
The below example demonstrates how we can handle incorrect values in the constructor by incorporating parameter validation, exception handling, and error reporting.
C++
#include <iostream>
#include <stdexcept>
using namespace std;
class Rectangle {
private :
double length;
double width;
public :
Rectangle( double l, double w)
: length(l)
, width(w)
{
if (length <= 0 || width <= 0) {
throw invalid_argument(
"Invalid dimensions. Length and width must "
"be positive." );
}
}
void print() const
{
cout << "Length: " << length
<< " units, Width: " << width << " units"
<< endl;
}
};
int main()
{
try {
Rectangle validRectangle(5.0, 10.0);
validRectangle.print();
Rectangle invalidRectangle(0.0, -3.0);
invalidRectangle.print();
}
catch ( const exception& e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
|
Output
Length: 5 units, Width: 10 units
Error: Invalid dimensions. Length and width must be positive.
Share your thoughts in the comments
Please Login to comment...