?? demo_exception_handling_2.cpp
字號:
//**********************************************************
//catch說明的捕獲異常的類型必須和throw引發異常的類型相匹配,
//若類型都不匹配,可以使用缺省的異常捕獲和處理: catch(...)
//注意: catch捕獲塊的順序很重要,因為順序匹配執行.
//**********************************************************
# include <iostream.h>
void trigger(int code)
{
try
{
if(code==0) throw code; //引發int類型的異常
if(code==1) throw 100; //引發int類型的異常
if(code==2) throw 100L; //引發long int類型的異常
if(code==3) throw 'x'; //引發char類型的異常
if(code==4) throw "x"; //引發char *類型的異常
if(code==5) throw 3.14f; //引發float類型的異常
if(code==6) throw 3.14; //引發double類型的異常
}
//若放到前面,則編譯器會給出6個錯誤警告
//指出后面的所有6個catch塊都不起作用了!
// catch(...)
// {
// cout<<"Catching default ..."<<endl;
// }
//throw-catch不但可以傳遞異常值,也可以傳遞異常值
catch(long int i)
{
cout<<"Catching integer : "<<i<<endl;
}
catch(char ch)
{
cout<<"Catching char : "<<ch<<endl;
}
catch(char *ch)
{
cout<<"Catching char * : "<<ch<<endl;
}
catch(float f)
{
cout<<"Catching float : "<<f<<endl;
}
catch(double d)
{
cout<<"Catching double : "<<d<<endl;
}
catch(...) //一般放在最后
{
cout<<"Catching default ..."<<endl;
}
return;
}
int main()
{
cout<<"Execute Function: trigger(0)"<<endl;
trigger(0);
cout<<endl;
cout<<"Execute Function: trigger(1)"<<endl;
trigger(1);
cout<<endl;
cout<<"Execute Function: trigger(2)"<<endl;
trigger(2);
cout<<endl;
cout<<"Execute Function: trigger(3)"<<endl;
trigger(3);
cout<<endl;
cout<<"Execute Function: trigger(4)"<<endl;
trigger(4);
cout<<endl;
cout<<"Execute Function: trigger(5)"<<endl;
trigger(5);
cout<<endl;
cout<<"Execute Function: trigger(6)"<<endl;
trigger(6);
cout<<endl;
return 0;
}
/*
Execute Function: trigger(0)
Catching default ...
Execute Function: trigger(1)
Catching default ...
Execute Function: trigger(2)
Catching integer : 100
Execute Function: trigger(3)
Catching char : x
Execute Function: trigger(4)
Catching char * : x
Execute Function: trigger(5)
Catching float : 3.14
Execute Function: trigger(6)
Catching double : 3.14
Press any key to continue
*/
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -