
異常是C 的一個非常核心的概念。在執行過程中發生不希望或不可能的操作時會發生異常。在C 中處理這些不希望或不可能的操作稱為異常處理。例外處理主要使用三個特定的關鍵字,它們是‘try’、‘catch’和‘throw’。 ‘try’關鍵字用於執行可能遇到異常的程式碼,‘catch’關鍵字用於處理這些異常,‘throws’關鍵字用於建立異常。 C 中的異常可以分為兩種類型,即STL異常和使用者定義的異常。在本文中,我們將重點放在如何建立這些自訂的異常。有關異常處理的更多詳細資訊可以在此處找到。
首先,我們看到如何使用一個單一的類別來建立自訂異常。為此,我們必須定義一個類別並拋出該類別的異常。
//user-defined class
class Test{};
try{
//throw object of that class
throw Test();
}
catch(Test t) {
....
}
#include <iostream>
using namespace std;
//define a class
class Test{};
int main() {
try{
//throw object of that class
throw Test();
}
catch(Test t) {
cout << "Caught exception 'Test'!" << endl;
}
return 0;
}
Caught exception 'Test'!
‘try’區塊會拋出該類別的異常,而‘catch’區塊只會捕捉該特定類別的異常。如果有兩個使用者定義的異常類,那麼就必須分別處理它們。
這個過程很簡單,如預期的那樣,如果有多個異常情況,每個都必須單獨處理。
//user-defined class
class Test1{};
class Test2{};
try{
//throw object of the first class
throw Test1();
}
catch(Test1 t){
....
}
try{
//throw object of the second class
throw Test2();
}
catch(Test2 t){
....
}
#include <iostream>
using namespace std;
//define multiple classes
class Test1{};
class Test2{};
int main() {
try{
//throw objects of multiple classes
throw Test1();
}
catch(Test1 t) {
cout << "Caught exception 'Test1'!" << endl;
}
try{
throw Test2();
}
catch(Test2 t) {
cout << "Caught exception 'Test2'!" << endl;
}
return 0;
}
Caught exception 'Test1'! Caught exception 'Test2'!
我們必須使用兩個不同的try-catch區塊來處理兩個不同類別的例外。現在我們來看看是否可以使用建構函數來建立和處理異常。
我們可以使用類別建構子來建立自訂異常。在下面的範例中,我們可以看到異常的拋出和處理都在類別構造函數內部進行管理。
#include <iostream>
using namespace std;
//define a class
class Test1{
string str;
public:
//try-catch in the constructor
Test1(string str){
try{
if (str == "Hello"){
throw "Exception! String cannot be 'Hello'!";
}
this->str = str;
}
catch(const char* s) {
cout << s << endl;
}
}
};
int main() {
Test1 t("Hello");
return 0;
}
Exception! String cannot be 'Hello'!
異常處理是C 提供的最重要的功能之一。我們可以繼承C 異常類別並使用它來實現異常處理,但這只是良好的實踐,不是創建自訂異常所必需的。繼承C 異常類別的好處是,如果有一個普通的catch語句捕獲std::exception,它可以處理任何使用者定義的異常而不需要知道具體細節。需要注意的是,'throws'語句只在'try'區塊內起作用,否則不起作用。 'catch'語句只能處理由使用者定義的類別或某些STL類別所拋出的例外。
以上是C++程式建立自訂異常的詳細內容。更多資訊請關注PHP中文網其他相關文章!