c++中try catch的用法
2016-07-02 10:52
761 查看
在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)
[html] view
plain copy
#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;
}
}
也可以自己定义异常类来进行处理:
[html] view
plain copy
#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;
}
同时也可以使用标准异常类进行处理:
[html] view
plain copy
#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;
}
[html] view
plain copy
#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;
}
}
也可以自己定义异常类来进行处理:
[html] view
plain copy
#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;
}
同时也可以使用标准异常类进行处理:
[html] view
plain copy
#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;
}
相关文章推荐
- 嵌入式C语言强化笔记--__I、 __O 、__IO
- 64位Win7,Win8和Win8.1使用VC++6.0方法。
- 分割字符串C++
- C++面试常错问题摘要
- 深入理解C++中public、protected及private用法
- c++基础
- C++11新标准的阻止拷贝方案
- MOOC C语言程序设计 第一周编程题
- socket穿透代理代码(C++版)
- 李洪强漫谈iOS开发[C语言-003]-开发概述程序设计语言
- 给正准备学习VC++朋友的建议
- MOOC C语言程序设计 基础1.0
- 李洪强漫谈iOS开发[C语言-002]-开发概述程序的本质与简单执行过程
- C语言32个关键字
- 李洪强iOS开发之OC语言前期准备
- 北理工c语言单项选择题
- new与delete创建对象
- VC++学习笔记之Windows数据类型(长期更新)
- C语言下的结构体间赋值的深度分析
- new与delete申请内存