網站首頁 編程語言 正文
C++原本的異常系統是這個樣子的:
調用what()方法時只返回異常的名稱,并沒有顯示拋出異常的位置和堆棧跟蹤,功能上顯得少許的貧瘠...
下面這個是我自己實現的改良版的異常處理系統:
可以看到詳細的信息,下面是實現過程。
一、模擬棧展開的過程
網上看到別人用一些很奇怪的方法來獲取堆棧信息,從而實現堆棧跟蹤。
個人覺得很費勁,而且還要安裝第三方庫。
于是我們可以寫一個類來模擬這個過程。
定義一個叫做ExceptionStackTrace的類:
class ExceptionStackTrace {
private:
const char** m_message_trace = nullptr; // 方法名數組
size_t* m_line_trace = nullptr; // 行數數組
int m_top; // 棧頂
int m_size; // 大小
public:
ExceptionStackTrace(int size);
void push(const char* message); // 入棧一個方法
void pop(); // 出棧一個方法
bool empty() const; // 判斷是否為空
int top() const; // 返回棧頂索引
int size() const; // 返回大小
void print_stack_trace() const; // 打印堆棧跟蹤信息
void throw_(SuperException except); // 拋出一個異常,需要繼承SuperException這個后面會講到
};
既然是模擬,所以需要在程序最前面定義一個靜態的對象,使用時在每一個函數的開始和結束部分加上這兩句:
static ExceptionStackTrace est = 128;
void method(...) {
est.push(__FUNCSIG__);
... // 異常拋出在這里可以被捕捉
est.pop();
}
main ...
當調用方法時,會在調用ExceptionStackTrace的push方法,將方法信息壓棧。
之后再執行方法內部的語句。
最后在將方法出棧,模擬方法已被調用完畢。
下面是實現代碼:
ExceptionStackTrace::ExceptionStackTrace(int size) {
// 尺寸不能是負數
if (size <= 0) throw std::exception("Size should greater than 0.");
m_message_trace = new const char*[size];
m_top = 0;
m_size = size;
}
void ExceptionStackTrace::push(const char* message) {
// 方法信息壓棧
m_message_trace[m_top] = message;
++m_top;
}
void ExceptionStackTrace::pop() {
// 方法信息出棧,棧空拋異常
if (this->empty()) throw std::exception("Exception stack trace empty!");
--m_top;
}
bool ExceptionStackTrace::empty() const {
return m_top == 0;
}
int ExceptionStackTrace::top() const {
return m_top;
}
int ExceptionStackTrace::size() const {
return m_size;
}
void ExceptionStackTrace::print_stack_trace() const {
// 從后往前,因為棧的性質后進先出
for (int i = m_top - 1; i >= 0; --i) {
printf(" At method \"%s\"\n", m_message_trace[i]);
}
}
void ExceptionStackTrace::throw_(SuperException except) {
// 拋出一個異常
printf("Unhandled exception: %s: %s\n", except.exception_name(), except.message());
this->print_stack_trace();
exit(-1);
}
二、新異常處理系統中異常的定義
異常包括信息和異常名稱,同時還需要支持自定義異常。
所以我們可以搞一個用于新異常系統的父類異常,自定義的異常全部繼承這個類即可。
父類的名字叫SuperException,下面是類結構:
#define M_GetName(data) #data // 宏定義,獲取字符串形式類的名稱
class SuperException {
private:
const char* m_exception_name = nullptr; // 異常名稱
const char* m_message = nullptr; // 異常消息
public:
// 構造函數
SuperException(const char* message, const char* exception_name = M_GetName(SuperException));
const char* message() const; // 獲取異常消息
const char* exception_name() const; // 獲取異常名稱
};
然后是實現部分:
SuperException::SuperException(const char* message, const char* exception_name) {
m_message = message;
m_exception_name = exception_name;
}
const char* SuperException::message() const {
return m_message;
}
const char* SuperException::exception_name() const {
return m_exception_name;
}
具體用法:
int main() {
est.push(__FUNCSIG__);
int i = 0;
scanf_s("%d", &i);
if (i == 128) est.throw_(SuperException("這是一個異常。"));
est.pop();
return 0;
}
當輸入128時:
三、超級運用
#include "ExceptionStackTrace.h"
static ExceptionStackTrace est = 128;
// 自定義一個異常
class IndexOutOfBoundsException : public SuperException {
public:
IndexOutOfBoundsException(const char* message, const char* exception_name = M_GetName(Exception))
: SuperException(message, exception_name) {
}
};
// 自定義一個異常
class BadArrayException : public SuperException {
public:
BadArrayException(const char* message, const char* exception_name = M_GetName(Exception))
: SuperException(message, exception_name) {
}
};
template<typename T> class Array {
private:
T* m_array;
size_t m_length;
private:
// 下標檢查
void index_check(size_t index) {
est.push(__FUNCSIG__);
if (index >= m_length) {
est.throw_(IndexOutOfBoundsException("Index out of bounds."));
}
est.pop();
}
public:
// 構造器
Array(size_t length) {
est.push(__FUNCSIG__);
m_length = length;
try {
m_array = new T[length];
} catch (std::bad_alloc) {
est.throw_(BadArrayException("Cannot create a Array object because no space."));
}
est.pop();
}
// 索引訪問
T& operator[](size_t index) {
est.push(__FUNCSIG__);
index_check(index);
est.pop();
return m_array[index];
}
};
int main() {
est.push(__FUNCSIG__);
Array<void*> a = 128;
a[129] = new char[16];
est.pop();
return 0;
}
結果:
為一的遺憾就是沒法加上行號文件等提示信息,如果能夠實現的話,我將會在下一篇博客中提及。
原文鏈接:https://blog.csdn.net/weixin_45061161/article/details/125993499
相關推薦
- 2022-10-16 python?math模塊使用方法介紹_python
- 2022-04-21 Android自定義View實現標簽流效果_Android
- 2022-07-19 安卓TextView的lineHeight*lineCount!=height問題,解決不支持滾動的
- 2021-12-12 Redis實現分布式鎖的實例講解_Redis
- 2022-10-03 react中使用useEffect及踩坑記錄_React
- 2023-01-14 C++應用Eigen庫對應實現matlab中部分函數問題_C 語言
- 2022-08-13 服務器上Redis主從復制和哨兵機制的配置
- 2022-10-26 Python實戰基礎之Pandas統計某個數據列的空值個數_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支