c++中try catch的用法
来源:互联网 发布:男生基本款帽子 知乎 编辑:程序博客网 时间:2024/06/11 18:54
在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)
- #include <iostream>
- #include <exception>
- using namespace std;
- int main () {
- try
- {
- throw 1;
- throw "error";
- }
- catch(char *str)
- {
- cout << str << endl;
- }
- catch(int i)
- {
- cout << i << endl;
- }
- }
也可以自己定义异常类来进行处理:
- #include <iostream>
- #include <exception>
- using namespace std;
- //可以自己定义Exception
- class myexception: public exception
- {
- virtual const char* what() const throw()
- {
- return "My exception happened";
- }
- }myex;
- int main () {
- try
- {
- if(true) //如果,则抛出异常;
- throw myex;
- }
- catch (exception& e)
- {
- cout << e.what() << endl;
- }
- return 0;
- }
同时也可以使用标准异常类进行处理:
- #include <iostream>
- #include <exception>
- using namespace std;
- int main () {
- try
- {
- int* myarray= new int[100000];
- }
- catch (exception& e)
- {
- cout << "Standard exception: " << e.what() << endl;
- }
- return 0;
- }
- 转自http://blog.csdn.net/gukesdo/article/details/6901991
0 0
- c++中try catch的用法
- java中try catch的用法
- js中try/catch/throw的用法
- asp.net中try catch的用法
- c++中try catch的用法
- c++中try catch的用法-1
- Java中try,catch,finally的用法
- c++中try catch的用法
- c++中try catch的用法
- c++中 try 和catch的用法
- c++中try catch的用法
- c#中 try catch的用法
- c++中try catch的用法
- c++中try catch的用法
- c++中try catch的用法
- Java中try,catch,finally的用法
- Java中try,catch,finally的用法
- MATLAB中try...catch...end的用法
- android中使用DisplayMetrics获取屏幕参数
- 安装python游戏图形框架pygame
- IOS应用提交所需的ICON
- 键盘缓存与安全键盘
- iOS域名解析
- c++中try catch的用法
- 【BZOJ1415】【Noi2005】聪聪和可可 概率DP 记忆化搜索
- 代理服务器-VPN-DNS
- 统计数字出现个数
- iOS工程中的info.plist文件的完整研究
- 测试庖丁解牛分词工具
- secureCRT The remote system refused the connection.
- android平台ssl单双向验证
- 如何搭建自己CDN服务器