lang:C++自定義異常類——用來處理自制編程語言的異常信息

前言

前篇lang:總結9種編程語言的語法來設計Suatin-lang裏設計了異常處理的信息,其實許多語言的異常信息格式都很相似。這篇用C++自定義異常類,用C++的異常處理來處理上層語言Suatin-lang的異常。


枚舉信息

枚舉所有的錯誤種類,打印異常信息的時候按這個來。

enum SuaError {
	NoDefinedError,				//未定義
	ZeroError,							//不該出現零的地方出現了零
	IOError,							//輸入輸出或文件操作出現問題
	ValueError,						//對已經有類型的變量傳遞了其他的類型
	OtherError                        //不屬於上面錯誤的其他類型錯誤
};	

顯示異常信息

//自定義異常類省略(仮)

/*
異常信息有:
	dir				  文件路徑
	lineNumber		  行數
	area              代碼作用域
	lineContent       該行內容
	description       異常描述

*/
template<int error>
void SelectException(std::string dir,int lineNumber,std::string area,std::string lineContent,std::string description) {
	std::string errorString = "Traceback at : File \"" + dir + "\",line " + std::to_string(lineNumber)+" in <"+area+">\n\t"+lineContent+"\n";
	switch (error) {
	case NoDefinedError:
		errorString += "NoDefinedError : " + description + "\n";
		break;
	case ZeroError:
		errorString += "ZeroError : " + description + "\n";
		break;
	case IOError:
		errorString += "IOError : " + description + "\n";
		break;
	case ValueError:
		errorString += "ValueError : " + description + "\n";
		break;
	case OtherError:
	default:
		errorString += "OtherError : " + description + "\n";
		break;
	}

	//std::cout << errorString << std::endl;
	throw SuaExcept(errorString);

}




void main(void) {


	try {
		int a = 0;
		if (a == 0) {
			SelectException<NoDefinedError>("E:/Can/Suatin/test.sua", 
							120,"module","sum = sum + i", "i is not defined");
		}
	}
	catch (SuaExcept& e) {
		std::cout << e.what()<<std::endl;
	}

	system("pause");
	
}

自定義異常類的錯誤示範

因爲我想傳遞一個待打印的異常信息過去,所以我這麼寫

class SuaExcept : public std::exception
{
	const char* error;
public:
	SuaExcept(std::string error) {
		this->error=error.c_str();
	}

	virtual const char* what()const throw() {
		return this->error;
	}
};

但是打印出亂碼!調試發現,error的確傳遞過去了,但是在捕獲異常時又調用了一次自定義異常類,得到的e地址沒變,說明捕獲到了!但是沒內容????

  • 暫時不知道是什麼問題。

正確的自定義異常類

class SuaExcept : public std::exception
{
public:
	SuaExcept(std::string error) : exception(error.c_str()){	}
};

輸出爲

Traceback at : File "E:/Can/Suatin/test.sua",line 120 in <module>
        sum = sum + i
NoDefinedError : i is not defined
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章