📄 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 + -