c ++创建类异常

bla*_*rex 1 c++ exception class

我在创建简单的类异常时遇到问题。

基本上,如果我在高尔夫比赛中的得分为 0,我必须抛出异常,因为该方法将得分减 1。

在这种情况下,我将如何创建一个简单的异常类?

我当前的代码看起来像这样,但我被卡住了,我擦除了所有内容。

//looking for when score[i]=0 to send error message 
class GolfError:public exception{
  public:
    const char* what(){}
    GolfError(){}
    ~GolfError(void);

  private:
    string message;
};
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 8

通常你来自 std::exception和覆盖virtual const char* std::exception::what(),就像下面的最小例子:

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Live on Wandbox

然后在测试分数的代码中抛出这个异常。但是,当发生“异常”并且程序无法继续进行时,您通常会抛出异常,例如无法写入文件。当您可以轻松纠正时,您不会抛出异常,例如当您验证输入时。


Mar*_*man 8

人们通常继承自std::runtime_error而不是基std::exception类型。它已经为您实现了 what()。

#include <stdexcept>

class GolfError : public std::runtime_error
{
public:
    GolfError(const char* what) : runtime_error(what) {}
};
Run Code Online (Sandbox Code Playgroud)