日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++實現并優化異常系統_C 語言

作者:阿莫·西林 ? 更新時間: 2022-09-24 編程語言

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

欄目分類
最近更新