一、标准的异常处理类exception
class exception;声明:
class exception {
public:
exception () throw();
exception (const exception&) throw();
exception& operator= (const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
}
所有由标准库抛出的对象都是通过exception派生出来的,因此所有标准的异常都可以被exception抓住。
二、exception的派生类型
bad_alloc //分配内存失败异常
bad_array_new_length //坏数组长异常
bad_cast //动态转换失败异常
bad_exception //为预期句柄异常
bad_function_call //坏调用异常
bad_typeid //空指针异常,用于获知一个变量的具体类型
bad_weak_ptr //坏弱指针
ios_base:failure //流异常
logic_error //逻辑错误异常
domain_error //域错误
future_error //将来错误
invalid_argument//无效参数
length_error //长度错误
out_of_range //越界错误
runtime_error //运行时错误异常
overflow_error //溢出错误
range_error //范围错误
system_error //系统错误
ios_base::failure //流异常
underflow_error //下流错误
三、实例
// exception_class.cpp : 定义控制台应用程序的入口点。
//
// exception example
#include "stdafx.h"
#include <iostream> //std::cerr
#include <typeinfo> //operator typeid
#include <exception> //std::exception
class Polymorphic {
virtual void member(){}
};
int _tmain(int argc, _TCHAR* argv[]) {
try
{
Polymorphic * pb = 0;
//typeid用于获知一个变量的具体类型。
typeid(*pb); // throws a bad_typeid exception
}
catch(std::exception& e)
{
std::cerr << "exception caught: " << e.what() << '\n';
}
return 0;
}
参考: