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

Why would you create your own custom exception class?

本文关键字:自定义异常 自己的 创建 为什么      更新时间:2023-10-16

我是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;
}

这是课程中的示例之一。

抛弃正常方式并抓住例外并不容易吗?我希望我的问题有意义,因为英语不是我的母语。

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

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

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(或其一个子类之一(继承自定义异常类是通常的,因此该函数的用户可以使用与标准异常相同的自定义异常来处理您的自定义异常,以防其不需要特殊处理。<<<<<<<<<<<<