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) ...
|
|