C++ 快速導覽 - 例外處理 try throw catch

例外處理 (exception handling) 為控制程式發生錯誤後的機制, C++ 使用 trythrowcatch 三個關鍵字 (keyword) 進行例外處理。



try 後面的大括弧用來放可能會發生錯誤的程式碼,在會發生錯誤的地方用 throw 丟出例外 (exception) , catch 依據例外的型態 (type) 進行處理。舉例如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
int main(void) {
    try {
        if (5 > 0) {
            throw "something wrong...";
        }
    }
    catch (const char* message) {
        std::cout << message << std::endl;
    }
 
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:trydemo01.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2013 年 1 月 */


這裡,如果 5 大於 0 就丟出 "something wrong..." 的例外
5
6
7
if (5 > 0) {
    throw "something wrong...";
}


對應到 catch 的部份,例外型態就是 const 的字元指標 (pointer)
9
10
11
catch (const char* message) {
    std::cout << message << std::endl;
}


編譯執行結果如下



例外的型態可以是標準程式庫 (standard library) 中的型態,或是自訂的型態,例如
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
 
struct BadValue : public std::exception {};
 
double divide(double a, double b) {
    if (b == 0) {
        throw BadValue();
    }
    return a / b; 
}
 
int main(void) {
    try {
        std::cout << divide(20, 5) << std::endl;
        std::cout << divide(20, 4) << std::endl;
        std::cout << divide(20, 3) << std::endl;
        std::cout << divide(20, 2) << std::endl;
        std::cout << divide(20, 1) << std::endl;
        std::cout << divide(20, 0) << std::endl;
    }
    catch (BadValue e) {
        std::cout << "something wrong..." << std::endl;
    }
 
    return 0;
}
 
/* 《程式語言教學誌》的範例程式
    檔名:trydemo02.cpp
    功能:示範 C++ 程式
    作者:張凱慶
    時間:西元 2013 年 1 月 */


這裡的 BadValue 繼承自標準程式庫中的 exception
3
struct BadValue : public std::exception {};


divide() 為可能發生例外的函數 (function) ,在分母 b 為 0 時就拋出例外
5
6
7
8
9
10
double divide(double a, double b) {
    if (b == 0) {
        throw BadValue();
    }
    return a / b; 
}


try 部份的程式碼會逐一執行,碰到發生例外就會跳到 catch 的部份,編譯執行結果如下



中英文術語對照
例外處理exception handling
關鍵字keyword
例外exception
型態type
指標pointer
標準程式庫standard library
函數function


您可以繼續參考
例外處理


相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁


參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial

C++ Primer, Fourth Edition, Stanley B. Lippman...

沒有留言: