在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;
}