![]() |
VOOZH | about |
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++
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.
The below example demonstrates how we can handle incorrect values in the constructor by incorporating parameter validation, exception handling, and error reporting.
Output
Length: 5 units, Width: 10 units Error: Invalid dimensions. Length and width must be positive.