【数据结构实战C++】11 异常类构建

【数据结构实战C++】11 异常类构建

作者 CodeAllen ,转载请注明出处


  • 异常的类型可以是自定义类类型
  • 对于类类型异常的匹配依旧是自上而下严格匹配
  • 赋值兼容原则在异常匹配中也适用

一般

  • -匹配子类异常的catch放在上部 //不然则无法catch子类
  • -匹配父类异常的catch放在下部

现代c++库必须包含充要的异常类族
异常类是数据结构类所依赖的 基础设施
在这里插入图片描述

异常类的功能定义(一般出现的就是下边这五种)
在这里插入图片描述

异常类中的接口定义

实验:创建异常类族(创建顶层父类)
main.cpp

#include <iostream>
#include <Exception.h>
using namespace std;
using namespace KKLib;
int main()
{
    try
    {
        THROW_EXCEPTION(ArithmeticException, "test");   //throw Exception("test", __FILE__, __LINE__);
    }
    catch(const Exception& e)
    {
        cout << "catch(const exception& e)" << endl;
        cout << e.message() <<endl;
        cout << e.location() <<endl;
    }
    return 0;
}

Exception.h

#ifndef EXCEPTION_H
#define EXCEPTION_H
namespace KKLib
{
#define THROW_EXCEPTION(e, m) (throw e(m, __FILE__, __LINE__))
class Exception
{
protected:
    char* m_message;
    char* m_location;
    void init(const char* message, const char* file, int line);
public:
    Exception(const char* message);
    Exception(const char* file, int line);
    Exception(const char* message, const char* file, int line);
    Exception(const Exception& e);
    Exception& operator = (const Exception& e);
    virtual const char* message() const;
    virtual const char* location() const;
    virtual ~Exception() = 0;
};
class ArithmeticException : public Exception   //继承自父类
{
public:
    ArithmeticException() : Exception(0) {}
    ArithmeticException(const char* message) : Exception(message) {}
    ArithmeticException(const char* file, int line) : Exception(file, line) {}
    ArithmeticException(const char* message, const char* file, int line) : Exception(message, file, line) {}
    ArithmeticException(const ArithmeticException& e) : Exception(e) {}
    ArithmeticException& operator =(const ArithmeticException& e)
    {
        Exception::operator =(e);
        return *this;
    }
};
}
#endif // EXCEPTION_H

设计原则:
可复用的代码库,尽量使用面向对象技术,尽量使用异常处理机制分离正常逻辑和异常逻辑

小结
现代c++库包含充要的异常类族
所有库中的数据结构类都依赖于异常机制
异常机制能够分离库中代码的正常逻辑和异常逻辑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章