异常的多态使用

  • 利用多态来实现 printError同一个接口调用
  • 抛出不同的错误对象,提示不同错误
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

//异常基类
class BaseException
{
public:
    virtual void printError()
    {}
};
class OutofRangeException :public BaseException
{
public:
    virtual void printError()
    {
        cout << "越界异常" << endl;
    }
};
class NullPointerException :public BaseException
{
public:
    virtual void printError()
    {
        cout << "空指针异常" << endl;
    }
};
void doWork()
{
    //throw NullPointerException();    //抛出空指针异常
    throw OutofRangeException(); //抛出越界异常
}
void test01()
{
    try
    {
        doWork();
    }
    catch (BaseException& e)     //BaseException类和其派生类
    {
        e.printError();         //捕获异常
    }
}

int main()
{
    test01();
    system("Pause");
    return 0;
}

结果:

异常的多态使用

 

相关文章:

  • 2021-10-18
  • 2021-07-21
  • 2021-09-27
  • 2022-02-20
  • 2022-12-23
  • 2021-05-05
  • 2022-12-23
  • 2021-09-14
猜你喜欢
  • 2021-04-01
  • 2021-09-13
  • 2021-06-22
  • 2021-11-21
  • 2021-11-25
  • 2021-12-06
  • 2021-07-25
相关资源
相似解决方案