try { // do something throw exception; } catch (exception declaration) { // excepetion handling code // throw or no } catch (exception declaration) { // another excepetion handling code // throw or no }
class myexception : public std::exception { public : myexception(std::string s) : exception(s.c_str()) { } virtual const char *what() const { return exception::what(); } }; void Func() { try{ int *p = NULL; if (p == NULL) { throw myexception("p is NULL"); } } catch(myexception e) { printf("%s\n", e.what()); throw; //重新抛出异常,异常类型为myexception } catch (std::exception e) { printf("%s", e.what()); } }
void Func() { try { // your code } catch(...) { // special operation for handling exception throw; } }
class myexception : public std::exception { public : myexception(std::string s) : exception(s.c_str()) { } virtual const char *what() const { return exception::what(); } }; class A { public : ~A() { printf("A's destructor\n"); } }; class B { public : ~B() { printf("B's destructor\n"); } }; void Func() { A a; throw myexception("p is NULL"); try{ int *p = NULL; if (p == NULL) { //throw myexception("p is NULL"); } } catch(myexception e) { printf("%s\n", e.what()); throw; } catch (std::exception e) { printf("%s", e.what()); } B b; } void Func2() { Func(); }
#include <cstdio> #include <cstdlib> #include <exception> #include <string> class myexception : public std::exception { public : myexception(std::string s) : exception(s.c_str()) { } virtual ~myexception() { printf("myexception's destructor\n"); } virtual const char *what() const { return exception::what(); } public : std::string _s; }; class A { public : ~A() { printf("A's destructor\n"); } }; class B { public : ~B() { printf("B's destructor\n"); } }; void Func() { A a; printf("dasd\n"); myexception e("p is NULL"); e._s = "haha"; try{ int *p = NULL; if (p == NULL) { throw e; } } catch(myexception &e) { e._s = "heiheihei"; printf("%s\n", e.what()); throw; } printf("%s\n", e._s.c_str()); B b; } void Func2() { try { Func(); } catch (myexception &e) { printf("Func2 : %s\n", e._s.c_str()); throw; } } int main() { try { Func2(); } catch (myexception &e) { printf("main: %s\n", e._s.c_str()); } printf ("hahah\n"); system("PAUSE"); return 0; }
异常类型 |
说明 |
exception |
最常见的问题 |
runtime_error |
只有在运行时才能检查的错误 |
range_error |
运行时错误:生成的结果超出了有意义的范围 |
overflow_error |
运行时错误:计算上溢 |
underflow_error |
运行时错误:计算下溢 |
logic_error |
程序逻辑错误 |
domain_error |
逻辑错误:参数对应的结果值不存在 |
invalid_error |
逻辑错误:无效参数 |
length_error |
逻辑错误:试图创建一个超出该类型最大长度的对象 |
out_of_range |
逻辑错误:使用一个超出有效范围的值 |