blayrex
blayrex

Reputation: 63

c++ create a class exception

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;
};

Upvotes: 3

Views: 17280

Answers (2)

Mark Waterman
Mark Waterman

Reputation: 961

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) {}
};

Upvotes: 9

vsoftco
vsoftco

Reputation: 56547

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.

Upvotes: 10

Related Questions