分享

c 中try catch的用法

 Kenshin0_0 2016-12-16

在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)

#include #include using namespace std;int main () { try { throw 1; throw 'error'; } catch(char *str) { cout << str << endl; } catch(int i) { cout << i << endl; }}


也可以自己定义异常类来进行处理:

#include #include using namespace std;//可以自己定义Exceptionclass 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 #include using namespace std;int main () { try { int* myarray= new int[100000]; } catch (exception& e) { cout << 'Standard exception: ' << e.what() << endl; } return 0;}


 

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多