c++ try catch
来源:互联网 发布:讨鬼传捏脸详细数据 编辑:程序博客网 时间:2024/06/04 18:57
在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;
- }
0 0
- 【c#】try...catch...finally
- C#-一個try catch樣例
- C语言的try and catch机制
- [C++] 异常控制try,catch用法
- c语言处理异常 二 -----try--catch
- [C++] 异常控制try,catch用法小结
- C语言try catch 异常检测实现
- C语言/PHP try-catch实现
- 【c#】异常处理:try catch throw
- C语言实现try catch处理
- try catch
- try{} catch{}
- try catch
- try...catch
- try{} catch(...){}
- try catch
- try-catch
- try catch
- c++ 之类成员函数作为函数的形参传递
- css负边距
- Winform无边框窗口拖动及改变窗口大小
- iframe跨域访问
- iOS学习之TableView02带Header
- c++ try catch
- 异常:Application failed 2 times due to AM Container
- Python练习程序(一)用户认证后,联系人信息查询
- Spring中AOP实例详解
- toast这么用避免连续多次点击产生的不好效果
- 【JavaScript】this关键字详解
- Android中的AlertDialog实现
- 用PHP模拟HTTP中的POST请求JSP网页,提交数据
- 序言