C++ 中的異常處理機制如何工作?
在 C++ 中,異常處理是處理執行時錯誤的過程。異常是在 C++ 中執行時丟擲的事件。所有異常都派生自 std::exception 類。它是一個可以處理的執行時錯誤。如果我們不處理異常,它會列印異常訊息並終止程式。
異常在 C++ 標準中定義為 `

C++ 中常見的異常類:
| 序號 | 異常及描述 |
|---|---|
| 1 | std::exception 這是一個異常,也是所有標準 C++ 異常的父類。 |
| 2 | std::bad_cast 由 dynamic_cast 丟擲的異常。 |
| 3 | std::bad_exception 此異常用於處理 C++ 程式中的意外異常。 |
| 4 | std::bad_alloc 通常由 new 丟擲。 |
| 5 | std::logic_error 此異常可以透過閱讀程式碼來檢測。 |
| 6 | std::runtime_error 此異常無法透過閱讀程式碼來檢測。 |
| 7 | std::bad_typeid 由 typeid 丟擲的異常。 |
關鍵詞
異常處理中有 3 個關鍵詞:try、catch 和 throw。
Try/Catch 塊
在 C++ 中,異常處理使用 try/catch 語句執行。可能發生異常的程式碼放在 Try 塊中。Catch 塊用於處理異常。
示例程式碼
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i=7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
}輸出
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
使用者自定義異常
我們可以透過繼承和重寫異常類的功能來定義我們自己的異常。
示例程式碼
#include <iostream>
#include <exception> using namespace std;
struct DivideByZero : public exception {
const char * what () const throw () {
return "My Exception";
}
};
int main() {
try {
throw DivideByZero();
} catch(DivideByZero& e) {
cout << "Exception caught" << endl; cout << e.what() << endl;
} catch(exception& e) {
}
}輸出
Exception caught My Exception what() = A public method provided by exception class and it has been overridden by all the child exception classes. It returns the cause of an exception.
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP