show you the code
//标准异常类
#include<iostream>
//头文件
#include<stdExcept>
using namespace std;
/*
标准异常类体系如下: 缩进层次表示继承关系
exception #include <exception>
runtime_error #include <stdexcept>
overflow_error
underflow_error
range_error
logic_error #include <stdexcept>
invalid_argument
length_error
out_of_range
domain_error
bad_alloc <new>
bad_exception
bad_cast <typeinfo>
bad_typeid <typeinfo>
它们都是类。需要引用的头文件已经标注。没有标的,那么它的头文件就是上一层的头文件。
*/
//自定义异常类,继承自exception
class myException :public exception
{
public:
myException(char* c)
{
m_p = c;
}
//what()函数返回错误信息
virtual char* what()
{
cout << "异常类型为 myException: "<< m_p << endl;
return m_p;
}
private:
char *m_p;
};
void test_func()
{
throw myException("出错啦!");
//throw bad_alloc();
}
int main()
{
try
{
test_func();
}
catch (myException& e)
{
e.what();
}
catch (bad_alloc& e)
{
e.what();
}
catch (...)
{
cout << "Unknown Error" << endl;
}
system("pause");
return 0;
}