C++异常处理分析
C++異常處理基本語法:
代碼如下:
代碼如下:
#include <iostream> using namespace std;int divide(int x, int y) {if (y == 0) throw y;return x / y; }void test01() {//試著去捕獲異常try{divide(10, 0);}/*catch (int){cout << "除數為0!" << endl;} */catch (int e){cout << "除數為" << e << "!" << endl;} }void callDivide(int x, int y) {divide(x, y); }void test02() {try {callDivide(10,0);}catch (int e){cout << "除數為" << e << "!" << endl;} }int main() {/*test01();*/test02();return 0; }棧解旋
異常被拋出后,從進入try塊起,這期間在棧上構造的所有對象,都會被自動析構。析構的順序與構造的順序相反,這一過程稱為棧的解旋。
代碼如下:
#include <iostream> using namespace std;class Person { public:Person(){cout << "對象構建" << endl;}~Person() {cout << "對象析構" << endl;} };int divide(int x, int y) {Person p1, p2;if (y == 0) throw y;return x / y; }void test01() {//試著去捕獲異常try{divide(10, 0);}/*catch (int){cout << "除數為0!" << endl;} */catch (int e){cout << "異常捕獲"<< endl;} }void callDivide(int x, int y) {divide(x, y); }int main() {test01();return 0; }測試結果:
異常接口聲明:
由于C++編譯器,忽略C++異常規范,所有在VS可以編譯通過運行,但是在linux是不行的。
代碼如下:
#include <iostream>using namespace std;//這個函數只能拋出int,float,char三種類型異常,拋出其他的就報錯 void func() throw(int ,float,char) {throw "abc"; }//不能拋出任何異常 void func02() throw() {throw - 1; }//可以拋出任何異常 void func03() {throw - 1; }int main() {try {func();}catch (char * str){cout << str << endl;}catch (int e){cout << "異常" << endl;}catch (...){cout << "未知異常" << endl;}return 0; }C標準異常類使用舉例和編寫自己的異常類:
代碼如下:
#include <iostream> #include <stdexcept> using namespace std;class Person { public:Person(){mAge = 0;}void setAge(int age){if (age < 0 || age > 100){throw out_of_range("年齡應該在0-100之間!");}this->mAge = age;}public:int mAge; };void test01() {Person p;try {p.setAge(1000);}/*catch (out_of_range e){cout << e.what() << endl;}*/catch (exception e){cout << e.what() << endl;}}class MyOutOfRange :public exception { public:MyOutOfRange(const char *error){pError = new char[strlen(error) + 1];strcpy(pError, error);}~MyOutOfRange(){if (pError != nullptr){delete[] pError;}}virtual const char *what() const{return pError;}public:char *pError; };void fun02() {throw MyOutOfRange("我自己的out_of_range!");}void test02() {try{fun02();}catch (exception &e){cout << e.what() << endl;} }int main() {/*test01();*/test02();return 0; }繼承在異常中的應用:
代碼如下:
總結
- 上一篇: 警方捣毁带货直播间“网络水军”团伙:一人
- 下一篇: 今年我国物联网连接数预计将超23亿 产值