I would like to write a custom Error class in C++. I am mostly used to Java (not used them a lot) so I would like to check here if my thought process on how to do this in C++ is correct.
Currently I got the following code:
class InvalidInput : public std::runtime_error {
public:
InvalidInput(const char* msg) : std::runtime_error(msg) {
}
};
I plan on using the cutsom error in a function as so:
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invalid input");
}
}
Before implementing it I would like to know if I am on the right track on how this should be done in C++ (as well as best practice). If there is a better way feel free to tell me as well.
For your solution as below.
create custome exception
class InvalidInput : public std::exception{
public:
InvalidInput(std::string msg):errorMsg_(msg){}
virtual const char* what() const throw()
{
return errorMsg_;
}
private:
std::string errorMsg_;
};
use of that custome excetion
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invlaid input");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.