我有一个Exception类,我想在它抛出之前设置更多信息。我可以创建Exception对象,调用它的一些函数然后抛出它而不用它的任何副本吗?
我发现的唯一方法是抛出指向对象的指针:
class Exception : public std::runtime_error
{
public:
Exception(const std::string& msg) : std::runtime_error(msg) {}
void set_line(int line) {line_ = line;}
int get_line() const {return line_;}
private:
int line_ = 0;
};
std::unique_ptr<Exception> e(new Exception("message"));
e->set_line(__LINE__);
throw e;
...
catch (std::unique_ptr<Exception>& e) {...}
但通常会避免通过指针抛出异常,那么还有其他方法吗?
还可以选择通过构造函数设置所有选项,但如果将更多字段添加到类中并且您希望对要设置的字段进行细粒度控制,则可以快速变为不可扩展:
throw Exception("message"); // or:
throw Exception("message", __LINE__); // or:
throw Exception("message", __FILE__); // or:
throw Exception("message", __LINE__, __FILE__); // etc.
答案 0 :(得分:9)
C ++异常类应该是可复制的或至少是可移动的。在您的示例中,使您的类可复制是添加默认复制构造函数的问题:
Exception(Exception const&) = default;
如果需要在异常类中封装一些不可复制和不可移动的状态,请将此类状态包装到std :: shared_ptr中。
答案 1 :(得分:6)
您可以创建数据保留类,例如ExceptionData
。然后创建ExceptionData
对象并调用它的方法。然后在ctor中使用Exception
创建std::move
对象,如:
ExceptionData data;
data.method();
throw Exception(std::move(data));
当然,ExceptionData
需要移动,你必须让ctor接受ExceptionData &&
(右值参考)。
如果你真的需要避免复制它会工作,但对我来说这感觉就像初步优化。想想你的应用程序中异常被抛出的频率,并且为此事情复杂化是非常值得的。
答案 2 :(得分:2)
使用std :: move?
怎么样?Exception e("message");
e.set_line(__LINE__);
throw std::move(e);
或者,您可以像这样创建一个Java-esque构建器:
class ExceptionBuilder;
class Exception : public std::runtime_error
{
public:
static ExceptionBuilder create(const std::string &msg);
int get_line() const {return line_;}
const std::string& get_file() const { return file_; }
private:
// Constructor is private so that the builder must be used.
Exception(const std::string& msg) : std::runtime_error(msg) {}
int line_ = 0;
std::string file_;
// Give builder class access to the exception internals.
friend class ExceptionBuilder;
};
// Exception builder.
class ExceptionBuilder
{
public:
ExceptionBuilder& with_line(const int line) { e_.line_ = line; return *this; }
ExceptionBuilder& with_file(const std::string &file) { e_.file_ = file; return *this; }
Exception finalize() { return std::move(e_); }
private:
// Make constructors private so that ExceptionBuilder cannot be instantiated by the user.
ExceptionBuilder(const std::string& msg) : e_(msg) { }
ExceptionBuilder(const ExceptionBuilder &) = default;
ExceptionBuilder(ExceptionBuilder &&) = default;
// Exception class can create ExceptionBuilders.
friend class Exception;
Exception e_;
};
inline ExceptionBuilder Exception::create(const std::string &msg)
{
return ExceptionBuilder(msg);
}
像这样使用:
throw Exception::create("TEST")
.with_line(__LINE__)
.with_file(__FILE__)
.finalize();