C++ Custom exception handling

Custom exception handling

1. Make custom exception class

According to std exception custom exception class inherit from std::exception like below.

    // exception.hxx
    class Exception : public std::exception {
    public: 
        Exception(int errorCode, const std::string &message) noexcept;
        virtual ~Exception() = default;
        virtual const char* what() const noexcept override;

    private:
        int errorCode;
        std::string m_message;
    };

    // exception.cpp
    #include "exception.hxx"

    Exception::Exception(int errorCode, const std::string &message) noexcept :
	    errorCode(erroCode), message(message)
    {
	    std::cout << this->message << std::endl;
    }

    const char *Exception::what() const noexcept
    {
    	return this->message.c_str();
    }

2. Throw custom exception

    // main.cpp
    #include "exception.hxx"
    #include <error.h>

    int main()
    {
        try {
            throw Exception(-EINVAL, "Invalid parameter.");
        } catch (const Exception &e) {
            std::cout << "Custom exception catched : " << e.what() << std::endl;
        }
    }

3. Trace exception meta information

Above 1~2 has problem that programmer can not check where exception occured.
Add meta information to exception handling.

    // exception.hxx
    // Exception(int errorCode, const std::string &message) noexcept;
    Exception(int errorCode, const char *file, const char *function,
			  unsigned int line, const std::string &message) noexcept;

    // get meta information from pre-processor
    #define __CUSTOM_THROW(ec, MESSAGE) \
        throw Exception(ec, __FILE__, __FUNCTION__, __LINE__, MESSAGE)

    #define ThrowExc(ec, MESSAGE) __CUSTOM_THROW(ec, MESSAGE)

    /// main.cpp
    
    // throw Exception(-EINVAL, "Invalid parameter.");
    ThrowExc(-EINVAL, "Invalid parameter.");

Keyword

try-block

Associates one or more exception handlers (catch-clauses) with a compound statement.

throw expression

Signals an erroneous condition and executes an error handler.
Provides consistent interface to handle errors through the throw expression.
All exceptions generated by the standard library inherit from std::exception.

c.f) Throw your own exception class based on runtime_error