打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C exception
userphoto

2011.03.02

关注

C++ exception

时间:2010-08-26 09:57:58来源:网络 作者:未知 点击:0
#include <iostream>
#include <exception>
using namespace std;

#include <iostream>
#include <exception>
using namespace std;

class A
{
public:
 A()
 {
    this->m_a = 0;
    this->m_st="";
 }
 //__declspec(nothrow)
  void fn(int i) throw(string ,int ) 
 {
  switch(i)
  {
  case 1:
   if(this->m_st.empty())
    throw exception("string is empty");
   break;
  case 2:
   if(this->m_a == 0 )
    throw exception(" 0 ²»ÄܳÉΪ³ýÊý");
   break;
  case 3:
   throw string("string");
      break;
  case 4:
   throw 10;
      break;
  default:
   throw 'a';
      break;
  }
   cout<<"every thing is ok";
 }
protected:
private:
 int m_a;
 string m_st;
};
int _tmain(int argc, _TCHAR* argv[])
{
 A a;
 try
 {
  a.fn(5 );
 }
 catch (std::exception &e)
 {
  cout<<e.what()<<endl;
 }
 catch (string &s)
 {
  cout<<s<<endl;
 }
 catch (int &i)
 {
  cout<<"i:"<<i<<endl;
 }
 catch (char &c)
 {
  cout<<"c:"<<c<<endl;
 }
 catch ( ... )   //Èý¸öÁ¬ÐøµÄ...¾ÍÊÇÍòÄܵġ£¡£
 {
  cout<<"ÍòÄܵÄÒì³£²¶×½ ";
 }
 return 0;
}

key: C++规范要求被做为异常抛出的对象必须被复制。

  即使被抛出的对象不会被释放,也会进行拷贝操作。

条款十二:理解“抛出一个异常”与“传递一个参数”或“调用一个虚函数”间的差异
从语法上看,在函数里声明参数与在catch子句中声明参数几乎没有什么差别:

  class Widget { ... };     //一个类,具体是什么类
                     // 在这里并不重要
void f1(Widget w);       // 一些函数,其参数分别为
void f2(Widget& w);      // Widget, Widget&,或
void f3(const Widget& w); // Widget* 类型
void f4(Widget *pw);
void f5(const Widget *pw);
catch (Widget w) ...       //一些catch 子句,用来
catch (Widget& w) ...      //捕获异常,异常的类型为
catch (const Widget& w) ... // Widget, Widget&, 或
catch (Widget *pw) ...     // Widget*
catch (const Widget *pw) ...


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
C++ 异常处理
(搬运工)异常处理与MiniDump详解(1) C++异常
c 中try catch的用法
5.3 出错处理 (Exception handling)
c++中的异常处理
C 与C++中的异常处理
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服