Reputation: 175
I am still a beginner and I do not really grasp the purpose of exceptions in a program.
When you throw an exception, you basically skip a (small or big) part of your program, so one of my questions would be : should an exception leads to the end of the program ?
Also, suppose we have a class Rectangle. It would be define by its length and its height like this :
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle(double length, double height)
{
if (length > 0 and heigth > 0) {
length_ = length;
height_ = height;
}
else {
// Throw an exception ? Use a convention ?
}
}
// other methods
private:
double length_;
double height_;
};
int main() {
// do stuff
return 0;
}
However, it would not make much sense to have a negative length or height. So should I throw an exception in the constructor ? Should I use an arbitrary convention and take their absolute value ? Should I prevent the user in the main() from passing negative arguments ?
Upvotes: 0
Views: 51
Reputation: 1269
Yes, in a constructor you do not have any other option to indicate an error but an exception. In cases where you can not assure a valid state of your object it is best to throw one. For example
#include <iostream>
#include <exception>
using namespace std;
struct Rectangle_exception : public std::runtime_error {
Rectangle_exception(const char* const message): std::runtime_error(message) {}
};
class Rectangle {
public:
Rectangle(double length, double height)
{
if (length > 0 && heigth > 0) {
length_ = length;
height_ = height;
}
else {
throw Rectangle_exception{"Invalid dimensions."};
}
}
// other methods
private:
double length_;
double height_;
};
For more informations about exceptions look in this FAQ or for "best practises" to error handling in C++ in the error section of CppCoreGuidelines
Sometimes exceptions are not desirable (because your company decided not to use them) but you still want to have some assertions. The CppCoreGuiidelines proposes Macros (and wants a language feature) named Expects
and Ensures
. Its planned that you can state preconditions and postconditions in the interface. For now these can be Macros with different behaviour depending on your compiler flags. For implementation details see here or here
class Rectangle {
public:
Rectangle(double length, double height)
{
Expects(length > 0 && height > 0);
length_ = length;
height_ = height;
}
// other methods
private:
double length_;
double height_;
};
Upvotes: 1