自定义异常类——为什么我们需要它

Custom Exception Class - Why do we need it?

本文关键字:为什么 自定义异常 我们      更新时间:2023-10-16

我正在阅读关于自定义异常…我就是这么做的。

#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
class myBase : public exception
{
public:
    myBase() {};
    virtual ~myBase(void) {};
    virtual const char* what() const { return "Hello, you have done a mistake"; }
};
class myDerived : public myBase
{
public:
    myDerived() {};
    virtual ~myDerived(void) {};
    const char* what() const { return "Hello, you have done a mistake in - derived class"; }
};
int main(void)
{
    try
    {
        throw myDerived();
    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    }
    getchar();
    return 0;
}

我明白了,我可以抛出我的自定义类对象,并且可以捕获它。我不明白你这么做的目的。有人能告诉我为什么我们需要自定义异常类吗?任何实际的例子都会帮助我理解使用自定义异常类的目的。

谢谢。

假设还有另一个用户定义的class也继承自class myBase:

class myDerived2 : public myBase {
public:
    myDerived2() {}
    virtual ~myDerived2() {}
};

假设你有一个try catch子句:

try {
  myDerived  A;
  myDerived2 B;
  ...
  /* to staff with both A and B */
  ...
} catch (std::exception& e){
  cout << e.what() << endl; 
}
  • 在上面的try - catch子句中,您通过以相同的方式处理myDerivedmyDerived2类型的异常来限制自己。

  • 如果您想以不同的方式处理myDerivedmyDerived2类型的抛出,该怎么办?

  • 那么你必须定义一个不同的try-catch子句:


try {
  myDerived  A;
  myDerived2 B;
  ...
  /* to staff with both A and B */
  ...
} catch (myDerived &d1) {
  /* treat exception of type myDerived */
} catch (myDerived &d2) {
  /* treat exception of type myDerived2 */
}
    从上面的例子中,我认为很明显,定义自定义异常为程序员提供了一个有价值和通用的工具,以更通用和专门的方式处理抛出。

在c++中你可以抛出任何你想要的类型,你不需要从std::exception继承。在不同的catch语句中捕获不同类型的能力很有用,因为您可以针对不同的条件抛出不同的异常类型。通过这种方式,您可以正确地处理不同的异常情况。

在这个简单的例子中,基于变量one,在catch语句中抛出和处理一个不同的异常。在本例中,"string"被打印到stdout

#include <iostream>
using namespace std;
int main(void)
{
    int one = 0;
    try
    {
        if(one)
            throw 1;
        else
            throw "string";
    }
    catch (int& i)
    {
        cout << i << endl;
    }
    catch (const char* s)
    {
        cout << s << endl;
    }
    return 0;
}