自定义异常示例:
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class MyException : public exception
{
public:
MyException() : message("Error."){}
MyException(string str) : message("Error : " + str) {}
~MyException() throw () {
}
virtual const char* what() const throw () {
return message.c_str();
}
private:
string message;
};
int main()
{
try
{
throw MyException();
}
catch(MyException& e)
{
std::cout << e.what() << std::flush;
}
catch(std::exception& e)
{
//其他的错误
}
}