我们如何通过消息抛出异常?

How can we throw an expcetion with a message?

我需要抛出异常并打印一些有用的消息。我试过这个:

throw std::exception("message"); 
throw std::exception(std::string("message"));

直到我发现 std::exception had only two constructors:

exception();
exception( const exception& other );

那么有什么好的方法呢?

你可以试试这样扔:

#include <iostream>

throw std::runtime_error(std::string("Failed: ") + message);
throw std::runtime_error("Error: " + message);

您也可以使用 boost::format

throw std::runtime_error(boost::format("There is an exception") % message);

std::exception 有一个内置的虚拟调用 .what() 来检索通用 catch 语句中异常的本地内容。由你来设定。

否则 except 和 catch 并考虑从 catch 中记录日志,这本身并不是一个坏习惯,但当然如果你在几个地方使用相同的异常,如果你想要一个集中的消息(最好如果您想记录捕获的位置而不是捕获的内容,请这样做。

广泛捕获,或者更糟糕的是捕获所有,都有其风险,并且因为捕获所有都无法知道您的特定异常的详细信息,what() 是我所知道的唯一有保证的共性。