C++中的异常处理(中)
2024-09-06 10:07:30
为什么要在catch中重新抛出异常?
#include <iostream>
#include <string> using namespace std; void Demo()
{
try
{
try
{
throw 'c';
}
catch(int i)
{
cout << "Inner: catch(int i)" << endl;
throw i;
}
catch(...)
{
cout << "Inner: catch(...)" << endl;
throw;
}
}
catch(...)
{
cout << "Outer: catch(...)" << endl;
}
} /*
假设: 当前的函数是第三方库中的函数,因此,我们无法修改源代码 函数名: void func(int i)
抛出异常的类型: int
-1 ==》 参数异常
-2 ==》 运行异常
-3 ==》 超时异常
*/
void func(int i)
{
if( i < )
{
throw -;
} if( i > )
{
throw -;
} if( i == )
{
throw -;
} cout << "Run func..." << endl;
} void MyFunc(int i)
{
try
{
func(i);
}
catch(int i)
{
switch(i)
{
case -:
throw "Invalid Parameter";
break;
case -:
throw "Runtime Exception";
break;
case -:
throw "Timeout Exception";
break;
}
}
} int main(int argc, char *argv[])
{
// Demo(); try
{
MyFunc();
}
catch(const char* cs)
{
cout << "Exception Info: " << cs << endl;
} return ;
}
#include <iostream>
#include <string> using namespace std; class Base
{
}; class Exception : public Base
{
int m_id;
string m_desc;
public:
Exception(int id, string desc)
{
m_id = id;
m_desc = desc;
} int id() const
{
return m_id;
} string description() const
{
return m_desc;
}
}; /*
假设: 当前的函数式第三方库中的函数,因此,我们无法修改源代码 函数名: void func(int i)
抛出异常的类型: int
-1 ==》 参数异常
-2 ==》 运行异常
-3 ==》 超时异常
*/
void func(int i)
{
if( i < )
{
throw -;
} if( i > )
{
throw -;
} if( i == )
{
throw -;
} cout << "Run func..." << endl;
} void MyFunc(int i)
{
try
{
func(i);
}
catch(int i)
{
switch(i)
{
case -:
throw Exception(-, "Invalid Parameter");
break;
case -:
throw Exception(-, "Runtime Exception");
break;
case -:
throw Exception(-, "Timeout Exception");
break;
}
}
} int main(int argc, char *argv[])
{
try
{
MyFunc();
}
catch(const Exception& e)
{
cout << "Exception Info: " << endl;
cout << " ID: " << e.id() << endl;
cout << " Description: " << e.description() << endl;
}
catch(const Base& e)
{
cout << "catch(const Base& e)" << endl;
} return ;
}
最新文章
- GJM: 设计模式 - 模板方法模式(Template Method)
- 《虚拟伙伴》AR增强现实应用开发总结
- css单位:em,rem解释
- table中的th td margin不生效
- C# lazy加载
- unity 引入 ios 第三方sdk
- 淘宝npm镜像使用方法
- 字符串ID转换成字符串名字
- ecshop邮件订阅按“订阅”没反应
- svn 钩子应用 - svn 提交字符限制, 不能为空
- Laravel 5 速查表
- Linux中断管理 (3)workqueue工作队列
- 设置SQLServer数据库内存
- 深入理解Java 8 Lambda(类库篇)
- Java String和Date的转换 Date类型操作
- [leetcode]134. Gas Station加油站
- 快速沃尔什变换 FWT 学习笔记【多项式】
- python-生产者消费者模式
- [Linux]--解决虚拟机中安装ubuntu不能自适应的问题
- 20145333《Java程序设计》课程总结