天天看點

c++中的異常---3(系統标準異常庫,編寫自己異常類)

系統标準異常庫

  1. #incldue
  2. out_of_range 等…
    #include<iostream>
     #include<string>
     using namespace std;
     
     //系統提供标準異常
     #include<stdexcept>
     
     
     
     
     class Person
     {
     public:
     	Person(string name, int age)
     	{
     		this->m_Name = name;
     		//年齡做檢測
     
     		if (age<0 || age>200)
     		{
     			//抛出越界異常
     			//throw out_of_range("年齡越界了");
     
     			throw length_error("長度越界了");
     		}
     	}
     
     	string m_Name;
     	int m_Age;
     };
     
     void test01()
     {
     	try
     	{
     		Person p("張三", 300);
     	}
     	catch (out_of_range &e)
     	{
     		cout << e.what()<<endl;
     	}
     	catch (length_error &e)
     	{
     		cout << e.what() << endl;
     	}
     }
     
     
     int main()
     {
     	test01();
     	system("pause");
     	return 0;
     }
               

編寫自己的異常類

  1. 自己的異常類需要繼承于系統提供的類 exception
  2. 重寫 虛析構 what()
  3. 内部維護錯誤資訊,字元串
  4. 構造時候傳入 錯誤資訊字元串,what傳回這個字元串
    #include<iostream>
     
     using namespace std;
     
     #include<string>
     using namespace std;
     
     //系統提供标準異常
     #include<stdexcept>
     
     
     class MyOutofRangeException :public exception
     {
     public:
     	MyOutofRangeException(string errorInfo)
     	{
     		this->m_ErrorInfo = errorInfo;
     	}
     	virtual ~MyOutofRangeException()
     	{
     
     	}
     	virtual const char *what()const
     	{
     		//傳回 錯誤資訊
     		//string 轉 char *     .c_str()
     		return this->m_ErrorInfo.c_str();
     
     	}
     
     
     	string m_ErrorInfo;
     };
     
     
     class Person
     {
     public:
     	Person(string name, int age)
     	{
     		this->m_Name = name;
     		//年齡做檢測
     
     		if (age<0 || age>200)
     		{
     			throw MyOutofRangeException(string ("我自己的年齡越界異常"));
     		}
     	}
     
     	string m_Name;
     	int m_Age;
     };
     
     void test01()
     {
     	try
     	{
     		Person p("張三", 300);
     	}
     	catch (MyOutofRangeException &e)
     	{
     		cout << e.what() << endl;
     	}
     	
     }
     
     
     int main()
     {
     	test01();
     	system("pause");
     	return 0;
     }