【數據結構實戰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++庫包含充要的異常類族
所有庫中的數據結構類都依賴於異常機制
異常機制能夠分離庫中代碼的正常邏輯和異常邏輯