异常处理

1.abort()
#include<cstdlib>
abort()会刷新文件缓冲区,向标准错误流输出untenable arguments to hmean()
2.try catch 对象
class bad_hmean{
  private:
    double v1;
    double v2;
  public:
    bad_hmean(double a=0,double b=0) :v1(a),v2(b){}
  void mesg();
};

inline void bad_hmean::mesg(){
  std::cout<<"hmean("<<v1<<","<<v2<<"):"<<"invalid arguments:a=-b";
}

try{

}catch(bad_hmean & bg){
  bg.mesg();
}

3.声明
double harm(double a) throw(bad_thing);//throw bad_thing 异常
double marm(double) throw();//不throw异常
double marm() noexcept;//C++11 不throw异常
throw声明和定义函数时候都需要书写
4.使用省略号捕获任意异常
try{
  duper();
}catch(bad_3 &be)
{//statements}
catch(...){
  statements;
}
5.异常类
#include<exception>
class bad_mean:public std::exception{
  public:
    const char * what(){return "bad arguments to hmean)";}
};
1.头文件包含
2.继承exception
3.what函数
4.使用
try{
  ...
}catch(std::exception &e){
  cout<<e.what()<<endl;
}
}

6.stdexcept类
(1)logioc_error
  有domain_error,invalid_arugment,length_error,out_of_bounds
(2)runtime_error
有range_error,overflow_error,underflow_error
使用举例
try{
  ...
}catch(out_of_bounds &oe){
  ...
}catch(logic_error & oe){
  ...
}catch(exception &oe){...}
7.new会抛出bad_alloc异常
8.未捕获的异常会调用terminate()函数,terminate()会调用abort()函数。
使用set_terminate()函数更改terminate()的行为。
例:
#include<exception>
using namespace std;
  void myQuit(){
  cout<<"Terminating due to uncaught exception.\n";
  exit(5);
}
set_terminate(myQuit);
类似的,使用set_unexpected()函数可更改Unexpected()的行为,Unexpected()的行为有
(1)可以调用terminate(),abort(),exit()
  (2)抛出异常
第二种抛出异常的行为会有以下结果
(1)新抛出的异常和原异常同类型,程序会企图寻找匹配的catch块
(2)新抛出的异常和原异常不同类型,且原异常不包含bad_exception类型,程序会调用terminate()函数
(3)新抛出的异常和原异常不同类型,但原异常包含bad_exception类型,程序会用bad_exception类型代替新抛出的异常
应用
#include<exception>
using namespace std;
void myUnexpected(){
    throw bad_exception();
  }

set_unexpected(myUnexpected);
最后调用
double Argh(double,double) throw(out_of_bounds,bad_exception);

try{
  x=Argh(a,b);
}catch(out_of_bounds & ex)
{...
}catch(bad_exception &ex){
  ...
}

9.在catch块内添加代码防止内存泄漏
void test2(int n){
  double *ar=new double[n];
try{
    if(oh_no)
      throw exception();
  }catch(exception &ex){
  delete[] ar;
  throw;
}

delete [] ar;
return;
}
posted @ 2024-08-21 14:51  zhongta  阅读(21)  评论(0)    收藏  举报