c++中的异常---3(系统标准异常库,编写自己异常类)
生活随笔
收集整理的這篇文章主要介紹了
c++中的异常---3(系统标准异常库,编写自己异常类)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
系統(tǒng)標準異常庫
#incldue
out_of_range 等…
#include<iostream>#include<string>using namespace std;//系統(tǒng)提供標準異常#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;}編寫自己的異常類
自己的異常類需要繼承于系統(tǒng)提供的類 exception
重寫 虛析構(gòu) what()
內(nèi)部維護錯誤信息,字符串
構(gòu)造時候傳入 錯誤信息字符串,what返回這個字符串
#include<iostream>using namespace std;#include<string>using namespace std;//系統(tǒng)提供標準異常#include<stdexcept>class MyOutofRangeException :public exception{public:MyOutofRangeException(string errorInfo){this->m_ErrorInfo = errorInfo;}virtual ~MyOutofRangeException(){}virtual const char *what()const{//返回 錯誤信息//string 轉(zhuǎn) 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;}總結(jié)
以上是生活随笔為你收集整理的c++中的异常---3(系统标准异常库,编写自己异常类)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怪异家族剧情介绍
- 下一篇: 第四代试管婴儿怎么做效果好