类与对象的异常
Cpp异常
#include <iostream> #include <string.h> 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(); }
类的异常
#include<iostream> using 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<iostream> #include <string> 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 << "正方体长度*an"; } cin.get(); }
面试100题1-100
单独整理成文档