找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 2326|回复: 0

C++标准异常类

[复制链接]
发表于 2014-10-17 22:38:58 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
    该话题为纯知识层级的,这里只做归纳、分析和总结
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:参数错误

  1. #include<bitset>
  2. #include<iostream>
  3. using namespace std;
  4. int main()
  5. {
  6.   try
  7.   {
  8.     bitset<32> bitset( string("11ba"));
  9.   }
  10.   catch(exception& e)
  11.   {
  12.     cerr<<"Caught"<<e.what()<<endl;
  13.     cerr<<"Type"<<tpeid(e).name()<<endl;
  14.   };
  15. }
复制代码


length_error:长度过长


  1. #include <vector>
  2. #include <iostream>

  3. using namespace std;

  4. template<class _Ty>
  5. class stingyallocator : public allocator<_Ty>
  6. {
  7. public:
  8.    template <class U>
  9.       struct rebind { typedef stingyallocator<U> other; };
  10.    _SIZT max_size( ) const
  11.    {
  12.          return 10;
  13.    };

  14. };

  15. int main( )
  16. {
  17.    try
  18.    {
  19.       vector<int, stingyallocator< int > > myv;
  20.       for ( int i = 0; i < 11; i++ ) myv.push_back( i );
  21.    }
  22.    catch ( exception &e )
  23.    {
  24.       cerr << "Caught " << e.what( ) << endl;
  25.       cerr << "Type " << typeid( e ).name( ) << endl;
  26.    };
  27. }
复制代码


out_of_range:超出数组范围

  1. #include <string>
  2. #include <iostream>

  3. using namespace std;

  4. int main() {
  5. // out_of_range
  6.    try {
  7.       string str( "Micro" );
  8.       string rstr( "soft" );
  9.       str.append( rstr, 5, 3 );
  10.       cout << str << endl;
  11.    }
  12.    catch ( exception &e ) {
  13.       cerr << "Caught: " << e.what( ) << endl;
  14.    };
  15. }
复制代码


overflow_error:算术溢出

  1. #include <bitset>
  2. #include <iostream>

  3. using namespace std;

  4. int main( )
  5. {
  6.    try
  7.    {
  8.       bitset< 33 > bitset;
  9.       bitset[32] = 1;
  10.       bitset[0] = 1;
  11.       unsigned long x = bitset.to_ulong( );
  12.    }
  13.    catch ( exception &e )
  14.    {
  15.       cerr << "Caught " << e.what( ) << endl;
  16.       cerr << "Type " << typeid( e ).name( ) << endl;
  17.    };
  18. }
复制代码



回复

使用道具 举报

本版积分规则

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-9-28 07:09 , Processed in 0.030179 second(s), 24 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表