C++ exception
時(shí)間:2010-08-26 09:57:58來源:網(wǎng)絡(luò) 作者:未知 點(diǎn)擊: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++規(guī)范要求被做為異常拋出的對(duì)象必須被復(fù)制。
即使被拋出的對(duì)象不會(huì)被釋放,也會(huì)進(jìn)行拷貝操作。
條款十二:理解“拋出一個(gè)異常”與“傳遞一個(gè)參數(shù)”或“調(diào)用一個(gè)虛函數(shù)”間的差異
從語法上看,在函數(shù)里聲明參數(shù)與在catch子句中聲明參數(shù)幾乎沒有什么差別:
class Widget { ... }; //一個(gè)類,具體是什么類
// 在這里并不重要
void f1(Widget w); // 一些函數(shù),其參數(shù)分別為
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) ...
|
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。