Open In App

How to Handle Incorrect Values in a Constructor?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to handle incorrect values in a constructor
  
#include <iostream>
#include <stdexcept>
using namespace std;
  
// class named rectangle
class Rectangle {
private:
    double length;
    double width;
  
public:
    // Constructor with the parameter validation
    Rectangle(double l, double w)
        : length(l)
        , width(w)
    {
        // Validate parameters
        if (length <= 0 || width <= 0) {
            throw invalid_argument(
                "Invalid dimensions. Length and width must "
                "be positive.");
        }
    }
    // Display dimensions
    void print() const
    {
        cout << "Length: " << length
             << " units, Width: " << width << " units"
             << endl;
    }
};
  
int main()
{
    try {
        // Creating a Rectangle object with the valid
        // dimensions
        Rectangle validRectangle(5.0, 10.0);
        validRectangle.print();
        Rectangle invalidRectangle(0.0, -3.0);
        invalidRectangle.print();
    }
    // catching exception raised in try block
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads