2016-02-05 63 views
-3

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

基本上,我不得不抛出一个异常,如果我在高尔夫球比赛成绩的数是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; 
}; 

回答

1

通常你从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; 
    } 
} 

Live on Wandbox

你则抛出此异常,对于分数测试代码。但是,通常在发生“特殊”情况时抛出异常,程序无法继续进行,如无法写入文件。当你可以很容易地纠正时,你不会抛出异常,例如当你验证输入时。

+0

这有助于!谢谢你,是的,我的任务需要我为此创建一个类例外,我得到了一切主要完成和测试,再次非常感谢你 – blayrex

+0

@blayrex顺便说一句,如果这里的答案之一解决你的问题到你的满意,你应该将来接受它,所以本网站的其他用户可以看到问题已解决。 – vsoftco

1

人们通常从std::runtime_error继承,而不是基于std::exception类型。它已经为你实现了什么()。

#include <stdexcept> 

class GolfError : public std::runtime_error 
{ 
public: 
    GolfError(const char* what) : runtime_error(what) {} 
}; 
+0

这是一个很好的观点+1。在OP的情况下,我想这是要走的路。如果你想要更多的控制异常,那么可能从'std :: exception'派生出来就更加灵活了。 – vsoftco