自定义异常类
1 class MyException 2 { 3 public: 4 MyException() 5 { 6 } 7 8 MyException(char* str) 9 { 10 msg = str; 11 } 12 13 MyException(MyException& rhs) 14 { 15 this->msg = rhs.msg; 16 } 17 18 std::string msg; 19 };
抛出异常
1 void CallWithException() 2 { 3 char msg[1024] = { 0 }; 4 sprintf(msg, "Exception: %s", "shit"); 5 throw MyException(msg); 6 }
捕捉异常
1 try 2 { 3 CallWithException(); 4 } 5 catch (MyException& e) 6 { 7 cout << e.msg; 8 }