Cpp異常
#include#include using namespace std; //標識錯誤的類型 class wrong { }; int intdiv(int a, int b) { try { if (b==0) { throw 10;//可以是任何對象 wrong(); } int c = a / b; return c; } catch (int data )//類型名 { cout << "除法異常已經處理"; return -1; } } int intdivA(int a, int b) { return a / b; } void main() { int x, y; cin >> x >> y; try { if (y==0) { throw "被除數為0"; } else if (x==0) { throw "除數為0"; } } catch (const char * s) { if (strcmp(s,"被除數為0")==0) { cout << "被除數為0異常,請重新輸入"; cin >> x >> y; } else if (strcmp(s, "除數為0") == 0) { cout << "除數為0異常,請重新輸入"; cin >> x >> y; } } std::cout << intdiv(x, y); cin.get(); cin.get(); cin.get(); }
類的異常
#includeusing namespace std; class wrong { }; class wrongA { }; class Array { public: Array(int num) { n = num; if (num<=0) { throw wrong(); } p = new int[num];//正確代碼在throw之後,不會被執行, for (int i = 0; i < num;i++) { p[i] = 0; } } int & operator[](int num) { if (num < 0 || num>= n) { throw wrongA(); } return p[num]; } protected: private: int *p; int n; }; void main() { try { Array myarrar(2); myarrar[-1]; } catch (wrongA e) { cout << "下標越界"; } catch (wrong e) { cout << "程序發生異常,數組大小必須大於等於1"; } cin.get(); } void mainA() { int a[3] = { 1, 2, 3 }; // printf("%d", 2[a]);//*(2+a) // printf("%d", a[9886655]); getchar(); }
#include#include using namespace std; class box //正方體 { public: box(int data) { cout << "開始構造"; if (data ==0) { zero z1; z1.errorcode = 212; throw z1; } else if ( data >0 && data<100) { throw small(); } else if (data>10000) { throw big(); } else if (data>100 && data<10000) { a = data; } else { throw wrong{}; } } int gettiji() { return a*a*a; } class zero { public: int errorcode; }; class wrong{}; class big{}; class small{}; private: int a;//變長 }; void main() { try { box newbox(0); } catch (box::zero w) { if (w.errorcode==22) { cout << "22號錯誤正方體長度不可以為0"; } else { cout << "fei22號錯誤正方體長度不可以為0"; } } catch (box::wrong) { cout << "正方體長度異常"; } catch (box::big) { cout << "正方體長度太長"; } catch (box::small) { cout << "正方體長度taiduan"; } cin.get(); }
單獨整理成文檔