您为什么要创建自己的自定义异常类?

时间:2019-07-30 16:11:58

标签: c++ exception

我是C ++的新手,我想了解为什么您要创建自己的自定义异常类。

我一直在阅读一些书籍和在线材料,它们指定您可以创建自己的异常类,但是它们没有解释为什么以及何时要创建异常类。

您为什么要创建此类

class ArrayException
{
private:
    std::string mError;
public:
    ArrayException(std::string error) : mError(error) {}
    const char *GetError()
{
    return mError.c_str();
}
};

在我们自定义的IntegerArray容器类中

    if(index < 0 || index >= GetLength())
        {
            throw ArrayException("Invalid index");
        }

main()

    int main()
    {
        IntArray arr;
    try
    {
        arr[6] = 100;

    }
    catch(ArrayException error)
    {
        std::cout << "An exception has been caught! " << 
        error.GetError() << std::endl;
    }
    return 0;

为什么不使用

if(index < 0 || index >= GetLength())
    {
        throw "Invalid index";

main()

int main()
{
IntArray arr;
try
{
    arr[6] = 100;

}
catch(const char *error)
{
    std::cout << "An exception has been caught! " << error << 
    std::endl;
}
return 0;

}

这是课程中的示例之一。

以正常方式抛出并捕获异常不是容易吗? 我希望我的问题有意义,因为英语不是我的母语。

1 个答案:

答案 0 :(得分:4)

  

为什么要创建自己的自定义异常类?

因为可以通过类捕获异常,并且自定义类允许捕获程序执行自定义catch子句。示例:

while(true) {
    try {
        do_something();
    } catch(custom_recoverable_exception& e) {
        // assume that we know about this exception; why it is thrown
        // and how to fix the problem in case it is thrown
        recover(e.custom_data);
        continue; // try again
    } catch(std::exception& e) {
        // some other exception; we don't know how to recover
        diagnose_exception(e); // write to a log or to standard output
        throw; // re-rhrow: Maybe the caller of this function knows how to proceed
    }

    proceed_with_the_loop();
  

以正常方式抛出并捕获异常不是容易吗?

抛出并捕获自定义类的对象 是正常的方法。

如果您要说的话,为什么不抛出一个指向字符串的指针:因为如果所有抛出的对象都具有相同的类型,那么您将无法以不同的方式处理一个抛出。


请注意,通常会从std::exception(或其子类之一)继承自定义异常类,以便该函数的用户可以在不需要自定义异常的情况下使用与标准异常相同的逻辑来处理您的自定义异常特殊处理。

相关问题