c++语言本身或者标准程序库跑出的所有异常,都派生自基类exception.这是其他数个标准异常的基类,他们共同构成一个类体系。
这些标准异常类别分为三组:
(1)语言本身所支持的异常
此类异常用以支撑某些语言特性。主要包括:
bad_alloc:new操作失败会抛出。
bad_cast:执行期间加在一个引用上面的动态性型别转换操作失败时抛出。
bad_typeid:执行RTTI时,交给typeid的参数为零或空指针时抛出
bad_exception:非预期的异常
(2)C++标准程序库发出的异常
总是派生自logic_error。逻辑错误是由于程序内部逻辑而导致的错误。逻辑错误是可以避免的,且在程序开始执行之前,能够被检测到。
domain_error:专业领域内的范畴 invalid_argument:无效参数,比如讲bitset以char而非0或1进行初始化 length_error:可能超越了最大极限,比如对着某个字符串附加太多字符。 out_of_range:参数不再预期范围内。例如在诸如array的容器或字符串string中采用一个错误索引。
(3)程序作用域之外发出的异常
总是派生自runtime_error,用来指出“不在程序范围内,且不容易回避”的事件。此类错误只在程序执行时才是可检测的。
举个例子:
#include <iostream>
#include <string>
#include <bitset>
#include <typeinfo>
#include <vector>
#include <stdexcept>
using namespace std;
int main()
{
//logic_error:out_of_range
try{
string str=("mirro");
string rstr("saft");
str.append(rstr,5,3);
cout<<str<<endl;
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//logic_error length_error
try{
int a[10];
for(int i=0;i<11;i++)
a[i]=11;
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//logic_error invalid_argument
try{
bitset<32> bitset(string("11001010101100001b100101010110000"));
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//logic_error: domain_error
try{
throw domain_error("The domain is error");
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//runtime_error: range_error
try{
throw range_error("The range is error");
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//runtime_error: overflow_error
try{
throw overflow_error("The overflow is error");
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
//runtime_error: underflow_error
try{
throw underflow_error("The underflow is error");
}
catch(exception &e)
{
cerr<<"catch:"<<e.what()<<endl;
cerr<<"Type:"<<typeid(e).name()<<endl;
}
return 0;
}
结果是:
catch:basic_string::append
Type:St12out_of_range
catch:bitset::_M_copy_from_ptr
Type:St16invalid_argument
catch:The domain is error
Type:St12domain_error
catch:The range is error
Type:St11range_error
catch:The overflow is error
Type:St14overflow_error
catch:The underflow is error
Type:St15underflow_error
对于一些不是特定类型的错误,比如我们要自己定义错误处理。可以先定义一个基类,再重载这个基类,实现各个错误重载。
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class ErrorBase{
public:
string reason;
int num;
};
class Exception1:public ErrorBase{
public:
Exception1()
{
reason="exception 1";
num=1;
}
};
class Exception2:public ErrorBase{
public:
Exception2()
{
reason="exception 2";
num=2;
}
};
void test()
{
}
int main()
{
try{
throw Exception2();
}
catch(const ErrorBase& e)
{
cout<<e.num<<" "<<e.reason<<endl;
}
}
本文前半部分引用自
http://www.dewen.net.cn/q/8659,感谢原作者。