一 普通异常
void main() {
try {
int age = 300;
if (age > 200) {
throw 9;
}
}
catch (int a) {
cout << "int 异常" << a<< endl;
}
system("pause");
}
结果:int 异常9
可以是其他存在的类型
void test1()
{
throw "测试!";
}
void test2()
{
throw exception("测试");
}
try {
test1();
}
catch (const char *m) {
cout << m << endl;
}
try {
test2();
}
catch (exception &e) {
cout << e.what() << endl;
}
二 多种类型的
(char * 先在 vs项目属性中设置符合模式)
void main() {
try {
int age = 300;
if (age > 200) {
throw "xxx";
}
}
catch (int a) {
cout << "int 异常" << a<< endl;
}
catch (char * b) {
cout << "char *b" << b << endl;
}
system("pause");
}
结果:char *bxxx
三 标准异常
类似于java中javaNullPointerException
class NullPointerException :public exception {
public :
NullPointerException(char * msg) :exception(msg){
}
};
void main() {
try {
int age = 300;
if (age > 200) {
throw NullPointerException("pgone");
}
}
catch (int a) {
cout << "int 异常" << a << endl;
}
catch (char * b) {
cout << "char *b" << b << endl;
}
catch (NullPointerException e) {
cout << "NullPointerException: " <<e.what() << endl;
}
system("pause");
}
结果:NullPointerException: pgone