现在的位置: 首页 > 综合 > 正文

c++ exception必须知道的东西(2)

2013年11月26日 ⁄ 综合 ⁄ 共 2096字 ⁄ 字号 评论关闭

C++标准库提供的逻辑异常包括以下内容。
   invalid_argument 异常,接收到一个无效的实参,抛出该异常。
   out_of_range 异常,收到一个不在预期范围中的实参,则抛出。
   length_error 异常,报告企图产生“长度值超出最大允许值”的对象。
   domain_error 异常,用以报告域错误(domain error)。
C++标准库提供的运行时异常包括以下内容。
   range_error 异常,报告内部计算中的范围错误。
   overflow_error 异常,报告算术溢出错误。
   underflow_error 异常,报告算术下溢错误。
   bad_alloc 异常,当new()操作符不能分配所要求的存储区时,会抛出该异常。它是由基类exception 派生的。
以上前 3 个异常是由runtime_error 类派生的。
例子:
# include<iostream>
# include<vector>
#include<stdexcept>   
using namespace std ;
int main() {
 vector<int> iVec ;
 iVec.push_back(1) ;
 iVec.push_back(2) ;
 iVec.push_back(3) ;
  try{
  cout << iVec.at(5) << endl ;
  }catch(out_of_range err) {
   cout << "êy×é????" << endl ;
  }
  system("pause");
}
综合经典实例:
#include<iostream>
using namespace std;
class Exception {
public :
 Exception(string _msg="") {
  msg = _msg ;
 }
 string getMsg() {
  return msg;
 }
protected:
 string msg ;
};

class PushOnFull:public Exception{
 PushOnFull(string msg=""):Exception(msg){}
};
class PopOnEmpty:public Exception{
public:
  PopOnEmpty(string msg = ""):Exception(msg){
 }
};
class StackException {
public:
 StackException(Exception _e , string _msg ):e(_e),msg(_msg) {  
 }
 Exception getSource(){
  return e ;
 } 
 string getMsg() {
  return msg ;
 }
private:
 Exception e ;
 string msg ;
};
template<class T>
class iStack {
public:
 iStack(int _capacity = 64) {
  capacity = _capacity ;
  data = new T[capacity] ;
  top = 0 ;
 }
 ~iStack() {
  cout <<"~iStack is called ... ... "<< endl ;
  delete[] data ;
 }
 void push(T t) throw(Exception) {
  if (top>=capacity) {
   throw Exception("???úá?") ;
  }
  data[top] = t ;
  top++ ;
 }
 T pop() throw(Exception){
  if (top <= 0 ) {
   throw Exception("???a??") ;
  }
  top--;
  T t = data[top] ;
  return t ;
 }
private:
 T* data ;
 int capacity ;
 int top ;
};
void test() {
 iStack<int> istack(10) ;
 try{
   for(int i = 0 ; i < 20 ; i++ ) {
   istack.push(i) ;
  }
   int p = istack.pop() ;
   cout << p << endl ;
  
 }catch(Exception e) {
  cout <<"2???á?"<< endl ;
  throw StackException(e,"±??a×°á?μ?òì3£") ;
 }
}
void test2() {
 iStack<int> istack(10) ;
 try{
   for(int i = 0 ; i < 20 ; i++ ) {
   istack.push(i) ;
  }
   int p = istack.pop() ;
   cout << p << endl ;
  
 }catch(...) {
  cout <<"?a??ê?±?D?òa?′DDμ?,??DD×ê?′êí???è"<< endl ;
  
 }
}
int main() {
 try{
  test() ;
     test2();
 }catch(StackException se) {
  cout << se.getSource().getMsg()<<"  " << se.getMsg()<< endl ;
 }
 system("pause");
}

 

 

【上篇】
【下篇】

抱歉!评论已关闭.