【C++】异常 Exception
生活随笔
收集整理的這篇文章主要介紹了
【C++】异常 Exception
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
異常
- 編程過程中的常見錯誤類型
- 語法錯誤
- 邏輯錯誤
- 異常
異常是一種在程序運行過程中可能會發生的錯誤(比如內存不夠)
異常如果沒有被處理,會導致程序終止。
如果覺得這個操作可能會拋出異常(系統拋出的),就使用try-catch,一旦try里發生異常就轉到catch部分
for (int i = 0; i < 99999; i ++) {try {int *p = new int[99999999]; // 可能會內存不夠拋出異常} catch(...) { // 寫...表示無論try里什么異常都會捕捉cout << "Exception. Memory not enough." << endl;break;} }-
也可以主動拋出異常
因為有些異常不會被主動拋出,不會導致程序終止。
int main() {try {int a = 10;int b = 0;int c = a / b;cout << c << endl;} catch (...) {cout << "Exception." << endl;}getchar();return 0; }以上代碼執行后不會輸出Exception也不會輸出c的值,直接閃退。盡管除0是異常操作,但程序并不會拋出異常,這樣很危險,因為捕捉不到異常,無法處理異常操作。
那么系統不拋就自己拋
int divide(int v1, int v2) {if (v2 == 0) {// throw exceptionthrow 999;}return v1 / v2; }int main() {try {int a = 10;int b = 0;cout << divide(a, b) << endl;} catch (int exception) {cout << "Exception:" << exception << endl;}getchar();return 0; }當除數為0的時候拋出異常,可以被catch,然后輸出Exception:999.
如果拋出的異常為字符串,catch異常的類型也要發生變化。
int divide(int v1, int v2) {if (v2 == 0) {// throw exceptionthrow "不能除以0";}return v1 / v2; }int main() {try {int a = 10;int b = 0;cout << divide(a, b) << endl;} catch (const char* exception) {cout << "Exception:" << exception << endl;}getchar();return 0; }輸出:Exception:不能除以0
-
try-catch格式:
可以捕捉不同類型的異常。
throw異常后,會在當前函數中查找匹配的catch,找不到就終止當前函數代碼,去上一層函數中查找。如果最終都找不到匹配的catch,整個程序就會終止。
-
-
異常的拋出聲明
為了增強可讀性和方便團隊協作,如果函數內部可能會拋出異常,建議函數聲明一下異常類型.
表示可能會拋出int類型的異常。 -
自定義異常類型
// 所有異常的基類 class Exception { private: public:virtual const char *what() const = 0;virtual int code() const = 0; };class DivideException: public Exception {const char *what() const {return "不能除以0";}int code() const {return 202; // 舉例} };class AddException: public Exception {const char *what() const {return "加法有問題";}int code() const {return 303;} }int divide(int v1, int v2) {if (v2 == 0) {// throw exceptionthrow DivideException();}return v1 / v2; }int main() {try {int a = 10;int b = 0;cout << divide(a, b) << endl;} catch (const Exception &exception) {cout << "DivideException:" << Exception.what() << endl;}getchar();return 0; } -
標準異常(std)
總結
以上是生活随笔為你收集整理的【C++】异常 Exception的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【C++】 类型转换
- 下一篇: 条件概率 and 条件概率的链式法则 a