主要学习这篇文章,讲得非常好很全面,不再做转载和复制:
我做一点补充:
如何抛出(throw)标准异常?
如下代码,需使用带字符串的构造函数
int a=10,b=0,c=1;
try{
if(b==0){
throw std::invalid_argument("你需要的错判提示"); // 这里
}
c=a/b;
} catch(const std::exception&e){
std::cerr<<"exception caught: "<<e.what()<<std::endl;
}
这样,就能抛出std::invalid_argument类型的异常了
其他的,std::bad_alloc,std::out_of_range等标准异常,也是同理
但要注意,std::exception不行,它是基类,没有构造函数,你只能使用std::bad_alloc这样的继承的子类
如果一定要用std::exception作为抛出对象,则预先在try-catch外面申请一个对象