admin管理员组文章数量:1289543
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?
本文标签: cImplementing safe custom exceptionStack Overflow
版权声明:本文标题:c++ - Implementing safe custom exception - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741400371a2376628.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论