【问题标题】:How to write a custom exception class derived from std::invalid_argument?如何编写从 std::invalid_argument 派生的自定义异常类?
【发布时间】: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&lt;char&gt; 的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


【解决方案1】:

而不是每次new char[],为什么不拥有std::string 数据成员?

class Foo_Exception : public std::exception /* ? */
{
    std::string msg;

public:
    Foo_Exception() {
        msg.reserve( 130000 );

        msg = "A string literal to be appended, ";
        msg += "another string, ";
        msg += "yet another one";
    }
    const char * what() const override { return msg.data(); }
    /* other members ? */
}

或者您可以从std 异常类型之一派生,该类型将字符串作为构造时的参数

class Foo_Exception : public std::runtime_error /* or logic_error */
{
public:
    Foo_Exception() : runtime_error("A string literal to be appended, " "another string, " "yet another one") {}
    /* other members ? */
}

但是,如果您只有字符串文字,您可以将它们拆分到多个源代码行,并有 零 个分配。

const char * what() const override { 
    return "A string literal to be appended, "
           "another string, "
           "yet another one";
}

【讨论】:

  • OP 声明函数必须返回char*。
  • @Caleth 为什么不.c_str()? .data() 也会这样做吗?
  • @SomethingSomething 它们是同义词(在 const 上下文中)
  • @SomethingSomething:在 C++11 之后,它们是同义词。它们都存在是因为标准过去不要求 .data() 返回一个以 0 结尾的字符串,这意味着 C++03 实现可能会延迟维护 0 终止符的工作,直到/除非调用 .c_string。但由于出于某些性能原因(例如,最好用其他写入完成写入),这不是一个好的实现选择,而且.c_str 不是const 也很糟糕,他们改变了这一点。 string c_str() vs. data()
  • std::runtime_error 拥有您需要的所有管道。不要重新发明轮子。
【解决方案2】:

我根据通过cmets和answer从其他人那里收到的反馈解决了这个问题。因此,我决定将自己的答案/解决方案留给未来的读者。

下面可以看到我经过深思熟虑和研究后得出的结论。这个解决方案相当简单易读。

这里是异常类接口:

Foo_Exception.h

#include <exception>


class Foo_Exception : public std::invalid_argument
{
public:
    explicit Foo_Exception( const std::string& what_arg );
};

这是它的实现:

Foo_Exception.cpp

#include "Foo_Exception.h"


Foo_Exception::Foo_Exception( const std::string& what_arg )
: std::invalid_argument( what_arg )
{
}

一个抛出Foo_Exception的函数:

Bar.cpp

#include "Bar.h"
#include "Foo_Exception.h"


void setCharacter( const char& c )
{
    if ( /* an invalid character (c) is passed to setCharacter */ )
    {
        std::string exceptionMsg;
        exceptionMsg.reserve( 130000 );

        exceptionMsg = "A string literal to be appended, ";
        exceptionMsg += std::to_string( /* a constexpr int */ );
        exceptionMsg += /* a char from a const unordered_set<char> */;

        throw Foo_Exception( exceptionMsg );
    }

    /*
        rest of the code
    */
}

如何处理异常:

main.cpp

#include <iostream>
#include "Bar.h"
#include "Foo_Exception.h"


int main( )
{
    try
    {
        setCharacter( '-' ); // The dash character is not valid! Throws Foo_Exception.
    }
    catch ( const Foo_Exception& e )
    {
        std::cerr << e.what( ) << '\n';
    }

    return 0;
}

变更摘要:

  1. 注意为什么不需要what() 函数,因为编译器会隐式生成它,因为Foo_Exception 继承自std::invalid_argument。

  2. 此外,创建异常消息的过程已从Foo_Exception 的ctor 移至函数setCharacter 的主体,该函数实际上引发了上述异常。这样,Foo_Exception 的 ctor 不负责创建消息。相反,它是在抛出的函数体中创建的,然后传递给 Foo_Exception 的 ctor 以初始化新的异常对象。

  3. 数据成员 std::string Exception_Msg 也已从 Foo_Exception 中删除,因为它不再需要了。

  4. 最后,try-catch 块被移动到main(),因此它现在环绕setCharacter() 并捕获它可能抛出的Foo_Exception 对象。

最后一句话: 任何进一步改进我的答案的建议都非常感谢。 非常感谢所有的反馈。

【讨论】:

  • 不错。请注意,您还可以利用多态性并将您的异常捕获为const std::invalid_argument &amp;e,具体取决于您的需要
  • 我不太喜欢里面的.reserve( 130000 )。这是一个“神奇数字”,没有关于您如何获得该数字的信息。鉴于我们看到的内容已放入异常文本中,这似乎有些过分。由于异常通常意味着程序的终止,因此通常不需要对异常路径进行优化。如果异常真的 is “异常”,或者您正在(ab-)使用异常机制来指示“正常”故障(您不应该这样做,因为可以通过来自setCharacter 的错误返回值更有效地处理)。
  • @DevSolar 13000 是一个随机数。就我而言,我需要 131 个字符。忽略那个数字。说到我的例子是否特殊,是的,你可能是对的。它可以由错误代码处理,但我不想使用代码。
猜你喜欢
  • 1970-01-01
  • 2019-04-07
  • 2021-09-09
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 2014-06-08
相关资源
最近更新 更多