【C/C++开发】try-cache-finnally捕获异常
在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;
- }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步