元始天尊 发表于 2014-10-17 22:38:58

C++标准异常类

    该话题为纯知识层级的,这里只做归纳、分析和总结
C++标准异常类结构:
exception:{bad_alloc,logic_error,runtime_error,bad_cast}
logic_error:{length_error,domain_error,out_of_range,invalid_argument}
runtime_error:{range_error,overflow_error,underflow_error}

invalid_argument:参数错误

#include<bitset>
#include<iostream>
using namespace std;
int main()
{
try
{
    bitset<32> bitset( string("11ba"));
}
catch(exception& e)
{
    cerr<<"Caught"<<e.what()<<endl;
    cerr<<"Type"<<tpeid(e).name()<<endl;
};
}


length_error:长度过长


#include <vector>
#include <iostream>

using namespace std;

template<class _Ty>
class stingyallocator : public allocator<_Ty>
{
public:
   template <class U>
      struct rebind { typedef stingyallocator<U> other; };
   _SIZT max_size( ) const
   {
         return 10;
   };

};

int main( )
{
   try
   {
      vector<int, stingyallocator< int > > myv;
      for ( int i = 0; i < 11; i++ ) myv.push_back( i );
   }
   catch ( exception &e )
   {
      cerr << "Caught " << e.what( ) << endl;
      cerr << "Type " << typeid( e ).name( ) << endl;
   };
}


out_of_range:超出数组范围

#include <string>
#include <iostream>

using namespace std;

int main() {
// out_of_range
   try {
      string str( "Micro" );
      string rstr( "soft" );
      str.append( rstr, 5, 3 );
      cout << str << endl;
   }
   catch ( exception &e ) {
      cerr << "Caught: " << e.what( ) << endl;
   };
}


overflow_error:算术溢出

#include <bitset>
#include <iostream>

using namespace std;

int main( )
{
   try
   {
      bitset< 33 > bitset;
      bitset = 1;
      bitset = 1;
      unsigned long x = bitset.to_ulong( );
   }
   catch ( exception &e )
   {
      cerr << "Caught " << e.what( ) << endl;
      cerr << "Type " << typeid( e ).name( ) << endl;
   };
}



页: [1]
查看完整版本: C++标准异常类