c++ try catch
2015-11-27 16:25
453 查看
在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)
[html]
view plaincopyprint?
#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 plaincopyprint?
#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 plaincopyprint?
#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 plaincopyprint?
#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; int main () { try { throw 1; throw "error"; } catch(char *str) { cout << str << endl; } catch(int i) { cout << i << endl; } }
也可以自己定义异常类来进行处理:
[html]
view plaincopyprint?
#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; //可以自己定义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 plaincopyprint?
#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;
}
#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++ 之类成员函数作为函数的形参传递
- c++ primer 4 数组和指针
- 类的继承
- C#引用C++Dll
- C++设计模式[二十二]模板方法模式
- C# C++类型对应
- C语言开发总结(十)
- C++中随机函数rand()和srand()的用法
- C/C++文件打开方式对文本内容的显示没有影响
- MySQL Connector/C++ 开发者指南简要阅读
- 红黑树的C++实现(2)
- MySQLConnector/C++连接方式二
- MySQLConnector/C++连接方式一
- c++操作符重载操作
- C++primer plus第六版课后编程练习答案7.1
- C++打印杨辉三角
- C++的基本数据类型
- 红黑树的C++实现(1)
- C++ 获得系统的所有用户
- 内存管理