Jakub
Jakub

Reputation: 19

Implementing safe custom exception

Note: I originally posted this question on Codereview, but was redirected here as more appropriate place.

I was trying to come up with some design to subclass built-in exceptions.

For simplest case I used something like this:

class SimpleCustomException : public std::runtime_error
{
public:
    using std::runtime_error::runtime_error;
};

Source: How to inherit from std::runtime_error?

which, from my understanding, should work, as it is basically std::runtime_error in disguise.

But, if I wish to pass some arbitrary additional data, say std::string, things get more complicated because exception should be copyable and at the same time it must not throw during stack unwinding because program will be terminated. So plain string is no-good because it may throw std::bad_alloc while copying.

So I came up with something simple like presented below. And my understanding is like this:

Constructor for this exception will attempt to create std::string through shared pointer. If this fails just nullptr is assigned as a fallback. Otherwise we have heap allocated data that is not copied (only pointer is) and it will not cause memory leak because it is reference counted.

#include <iostream>
#include <string>
#include <memory>

class CustomException : public std::runtime_error
{
public:
    CustomException(const std::string &what, const std::string &err_data) noexcept
        : std::runtime_error(what)
    {
        /* We try to allocate the data, as fallback just pass nullptr */
        try {
            this->error_data = std::make_shared<std::string>(err_data);
        } catch (const std::bad_alloc &e) {
            this->error_data = nullptr;
        }
    }

    std::shared_ptr<std::string> what_data() const noexcept
    {
        return error_data;
    }

private:
    std::shared_ptr<std::string> error_data;
};

int main()
{
    try {
        throw CustomException("HELLO", "WORLD");
    } catch (const CustomException &e) {
        std::string message = e.what();
        std::string extra_data;
        if (e.what_data()) {
            extra_data = *e.what_data();
        }
        std::cout << "Caught exception with message: " << message << std::endl;
        std::cout << "And extra data: " << extra_data << std::endl;
    }

    return 0;
}

I also found this post where similar issue is addressed, but I would like to know some feedback on this "concrete" implementation. Most importantly, how safe and reliable it is and can it be improved?

Upvotes: 1

Views: 65

Answers (0)

Related Questions