如何正确抛出一个需要的不仅仅是构造函数的异常

How to properly throw an exception which needs more than just a constructor?

本文关键字:不仅仅是 异常 构造函数 一个 何正确      更新时间:2023-10-16

>我有一个异常类,我想在抛出它之前设置更多信息。我可以创建 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.

C++异常类应该是可复制的或至少是可移动的。在您的示例中,使类可复制是添加默认复制构造函数的问题:

Exception(Exception const&) = default;

如果需要在异常类中封装一些不可复制和不可移动的状态,请将此类状态包装到 std::shared_ptr 中。

您可以创建一个数据保存类,例如 ExceptionData 。然后创建ExceptionData对象并调用它的方法。然后在 ctor 中使用std::move创建Exception对象,如下所示:

ExceptionData data;
data.method();
throw Exception(std::move(data));

当然,ExceptionData必须是可移动的,并且您必须具有接受ExceptionData &&的ctor(右值引用(。

如果你真的需要避免复制,它会起作用,但对我来说,这感觉就像是初步优化。想想你的应用中抛出异常的频率,以及让事情复杂化真的值得吗?

使用 std::move 怎么样?

Exception e("message");
e.set_line(__LINE__);
throw std::move(e);

或者,您可以创建一个 Java 式构建器,如下所示:

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();
相关文章: