Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 916
blayrex Avatar asked May 10 '26 19:05

blayrex


2 Answers

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.

like image 191
vsoftco Avatar answered May 13 '26 08:05

vsoftco


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) {}
};
like image 36
Mark Waterman Avatar answered May 13 '26 08:05

Mark Waterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!