简体   繁体   中英

Does C++ have an equivalent to .NET's NotImplementedException?

Does the standard library of C++ contain an exception equivalent to .NET's NotImplementedException?

If not, what are the best practices to handle incomplete methods that I intend to complete later on?

In the spirit of @dustyrockpyle, I inherit from std::logic_error but I use that class's string constructor, rather than overriding what()

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

You can inherit from std::logic_error, and define your error message that way:

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

I think doing it this way makes catching the exception more explicit if that's actually a possibility. Reference to std::logic_error: http://www.cplusplus.com/reference/stdexcept/logic_error/

Since this is just a temporary exception that does not carry any application meaning, you can just throw a char const* :

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

A good practice would be for your application to define its own set of exceptions, including one for unimplemented method, if that is needed. Make sure you inherit your exception type from std::exception so that callers of exception throwing functions can catch the error in a uniform way.

Just one possible way to implement a 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;
};

Here's my variation of this, which will show the function name and your own message.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM