| try { //可能引发异常的代码 } catch(type_1 e) { // type_1类型异常处理 } catch(type_2 e) { // type_2类型异常处理 } catch (...)//会捕获所有未被捕获的异常,必须最后出现 { } |
| #include <stdio.h> //定义Point结构体(类) typedef struct tagPoint { int x; int y; } Point; //扔出int异常的函数 static void f(int n) { throw 1; } //扔出Point异常的函数 static void f(Point point) { Point p; p.x = 0; p.y = 0; throw p; } int main() { Point point; point.x = 0; point.y = 0; try { f(point); //抛出Point异常 //f(1); //抛出int异常 } catch (int e) { printf("捕获到int异常:%d\n", e); } catch (Point e) { printf("捕获到Point异常:(%d,%d)\n", e.x, e.y); } return 0; } |
| namespace std { //exception派生 class logic_error; //逻辑错误,在程序运行前可以检测出来 //logic_error派生 class domain_error; //违反了前置条件 class invalid_argument; //指出函数的一个无效参数 class length_error; //指出有一个超过类型size_t的最大可表现值长度的对象的企图 class out_of_range; //参数越界 class bad_cast; //在运行时类型识别中有一个无效的dynamic_cast表达式 class bad_typeid; //报告在表达试typeid(*p)中有一个空指针p //exception派生 class runtime_error; //运行时错误,仅在程序运行中检测到 //runtime_error派生 class range_error; //违反后置条件 class overflow_error; //报告一个算术溢出 class bad_alloc; //存储分配错误 } |
| class exception { public: exception() throw(); exception(const exception& rhs) throw(); exception& operator=(const exception& rhs) throw(); virtual ~exception() throw(); virtual const char *what() const throw(); }; |
| #include <iostream> #include <exception> using namespace std; class myexception:public exception { public: myexception():exception("一个重载exception的例子") {} }; int main() { try { throw myexception(); } catch (exception &r) //捕获异常 { cout << "捕获到异常:" << r.what() << endl; } return 0; } |
| catch (exception &r) |