【发布时间】:2021-12-23 19:10:15
【问题描述】:
我应该如何编写一个高效的异常类来显示可以通过在运行时修复源代码错误来防止的错误?
这就是我选择std::invalid_argument的原因。
我的异常类(显然不工作):
class Foo_Exception : public std::invalid_argument
{
private:
std::string Exception_Msg;
public:
explicit Foo_Exception( const std::string& what_arg );
virtual const char* what( ) const throw( );
};
explicit Foo_Exception::Foo_Exception( const std::string& what_arg ) // how should I write this function???
{
Exception_Msg.reserve( 130000 );
Exception_Msg = "A string literal to be appended, ";
Exception_Msg += std::to_string( /* a constexpr int */ );
Exception_Msg += /* a char from a const unordered_set<char> */;
}
const char* Foo_Exception::what( ) const throw( )
{
return Exception_Msg.c_str( );
}
一个抛出 Foo_Exception 的 if 块:
void setCharacter( const char& c )
{
if ( /* an invalid character (c) is passed to setCharacter */ )
{
try
{
const Foo_Exception foo_exc;
throw foo_exc;
}
catch( const Foo_Exception& e )
{
std::cerr << e.what( );
return;
}
}
/*
rest of the code
*/
}
int main( )
{
setCharacter( '-' ); // dash is not acceptable!
return 0;
}
如您所见,我需要将Exception_Msg 与一些子字符串连接起来以形成完整的消息。这些子字符串不仅是字符串文字,而且是来自静态std::unordered_set<char> 的constexpr ints 和chars。这就是我使用 std::string 的原因,因为它具有易于使用的 string::operator+=。不用说,我的目标是将堆分配减少到只有 1。
另一个非常重要的问题是我应该将处理程序(try-catch)放在哪里?在main() 内包裹setCharacter() 还是将其保留在setCharacter 内?
请制作一个与上述类似的良好且标准的自定义异常类。或者自己写。提前致谢。
【问题讨论】:
-
不,没有办法从
std::string提取缓冲区。您必须照常使用new和std::copy。 -
XY 问题。 为什么你“必须返回
char *”?除非与遗留代码交互,否则不需要 C 样式字符串... -
您可以将
std::string error_message之类的内容添加为Foo_Exception的成员吗?如果是这样,您可以return error_message.c_str() -
为什么不将
std::string对象定义为Foo_Exception类的类成员?这样你就不需要处理new和delete。刚刚注意到这与@MarekKlein 所写的建议相同 -
异常的基本思想是在抛出异常的点创建消息,而不是在查询异常的点(所在的环境发生了异常,它的所有信息都已经消失了)。因此,在
.what()中组装消息的整个概念是有缺陷的。您可以使用std::runtime_error并完成它。如果你需要一个自定义异常类——因为你想将catch ( Foo_Exception ... )与std::exception分开——然后从std::runtime_error派生。你的问题本来就不存在。
标签: c++ exception c-strings stdstring micro-optimization