📄 demo_exception_handling_4_c.cpp
字号:
//*******************************************************
// 演示在函数嵌套调用的情况下:异常逐层传递,检测处理异常.
//*******************************************************
// 在同级成对try-catch结构中:
// 异常信息被throw抛出(注意:可能在此时创建异常对象)后,
// 一旦被catch捕获,异常信息立即析构消失,随后处理异常,
// 或者将捕获到的异常再次抛出(注意:只能在在catch块中
// 捕获后,才能在该catch块中由throw再次抛出),到外一层
// try-catch结构中等待捕获处理.
// 若没有被catch捕获,则跳过try块随后语句,到外一层
// try-catch结构中等待类型匹配的catch捕获处理.
//*******************************************************
# include <iostream.h>
void trigger()
{
cout<<" begin of trigger()"<<endl;
try
{
cout<<" begin of try in trigger()"<<endl;
cout<<" throw exception in try"<<endl;
throw "exception"; //引发char*类型的异常
cout<<" end of try in trigger()"<<endl;
}
catch(char* message) //捕获char*类型异常并作处理
{
cout<<" begin of catch in trigger()"<<endl;
cout<<" catch "<<message<<" in trigger()"<<endl;
//异常只能由catch语句中由不带参数的throw语句
//将捕获的异常再次抛出,传递给上一层try-catch块而重新捕获处理
cout<<" throw exception again in trigger()"<<endl;
throw;
cout<<" end of catch in trigger()"<<endl;
}
cout<<" end of trigger()"<<endl;
return;
}
int main()
{
cout<<"begin of main()"<<endl;
//检测以下语句中的函数调用是否产生异常
try
{
cout<<"try in main()"<<endl;
trigger();
}
//捕获char*类型异常并作处理
catch(char* message)
{
cout<<"catch "<<message<<" in main()"<<endl;;
}
cout<<"end of main()"<<endl;
return 0;
}
/*
begin of main()
try in main()
begin of trigger()
begin of try in trigger()
throw exception in try
begin of catch in trigger()
catch exception in trigger()
throw exception again in trigger()
catch exception in main()
end of main()
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -