C ++是否具有与.NET的NotImplementedException相同的功能?

时间:2014-06-28 18:53:20

标签: c++ exception-handling

C ++标准库是否包含与.NET的NotImplementedException等效的异常?

如果没有,处理我打算稍后完成的不完整方法的最佳做法是什么?

5 个答案:

答案 0 :(得分:34)

本着@dustyrockpyle的精神,我继承自std::logic_error,但我使用该类的字符串构造函数,而不是覆盖what()

class NotImplemented : public std::logic_error
{
public:
    NotImplemented() : std::logic_error("Function not yet implemented") { };
};

答案 1 :(得分:24)

您可以从std :: logic_error继承,并以这种方式定义错误消息:

class NotImplementedException : public std::logic_error
{
public:
    virtual char const * what() const { return "Function not yet implemented."; }
};

我认为这样做可以使异常更明确,如果这实际上是可能的话。 对std :: logic_error的引用: http://www.cplusplus.com/reference/stdexcept/logic_error/

答案 2 :(得分:3)

由于这只是一个暂时的异常,没有任何应用含义,你可以抛出一个char const *:

int myFunction(double d) {
    throw "myFunction is not implemented yet.";
}

答案 3 :(得分:3)

一个好的做法是让您的应用程序定义自己的一组异常,包括一个未实现的方法,如果需要的话。确保从std::exception继承您的异常类型,以便异常抛出函数的调用者能够以统一的方式捕获错误。

实现 NotImplementedException 的一种可能方式:

class NotImplementedException
    : public std::exception {

public:

    // Construct with given error message:
    NotImplementedException(const char * error = "Functionality not yet implemented!")
    {
        errorMessage = error;
    }

    // Provided for compatibility with std::exception.
    const char * what() const noexcept
    {
        return errorMessage.c_str();
    }

private:

     std::string errorMessage;
};

答案 4 :(得分:1)

这是我的变体,它将显示功能名称和您自己的信息。

class NotImplemented : public std::logic_error
{
private:

    std::string _text;

    NotImplemented(const char* message, const char* function)
        :
        std::logic_error("Not Implemented")
    {
        _text = message;
        _text += " : ";
        _text += function;
    };

public:

    NotImplemented()
        :
        NotImplemented("Not Implememented", __FUNCTION__)
    {
    }

    NotImplemented(const char* message)
        :
        NotImplemented(message, __FUNCTION__)
    {
    }

    virtual const char *what() const throw()
    {
        return _text.c_str();
    }
};