I'm having trouble creating a simple class exception.
Basically, I have to throw an exception if my number of score on a golf game is 0, because the method decreases the score by 1.
How would I create a simple exception class in this case?
My current code looks like this, but I'm stuck.
// looking for when score[i] = 0 to send error message
class GolfError : public exception {
public:
const char* what() {}
GolfError() {}
~GolfError(void);
private:
string message;
};
Usually you derive from std::exception and override virtual const char* std::exception::what(), like in the minimal example below:
#include <exception>
#include <iostream>
#include <string>
class Exception : public std::exception
{
std::string _msg;
public:
Exception(const std::string& msg) : _msg(msg){}
virtual const char* what() const noexcept override
{
return _msg.c_str();
}
};
int main()
{
try
{
throw Exception("Something went wrong...\n");
}
catch(Exception& e)
{
std::cout << e.what() << std::endl;
}
}
Live on Wandbox
You then throw this exception in the code that tests for the score. However, you usually throw an exception whenever something "exceptional" happen and the program cannot proceed further, like impossibility of writing into a file. You don't throw an exception when you can easily correct, like e.g. when you validate input.
People often inherit from std::runtime_error instead of the base std::exception type. It already implements what() for you.
#include <stdexcept>
class GolfError : public std::runtime_error
{
public:
GolfError(const char* what) : runtime_error(what) {}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With