Kodewick
開始學 →
異常:try 和 catch26 / 30

C++ 異常

第 26 課,共 30 課 · 第 6 部分 · 繼承和模板 · 約 25 分鐘

C++ 用 throw 丟擲異常,用 try { … } catch (const std::exception& e) { … } 接住,e.what() 是出錯的說明;at()、std::stoi 出錯時都會丟擲異常。

函數出了錯,怎麼告訴呼叫它的人?老辦法是回傳一個特殊的值,比如「算不出來就返回 0」。可要是 0 本身也是一個正常的答案呢?

main.cpp
1#include <iostream>2#include <vector>3 4double average(const std::vector<double>& temps) {5    if (temps.empty()) {6        return 0;7    }8    double total = 0;9    for (double t : temps) {10        total += t;11    }12    return total / temps.size();13}14 15int main() {16    std::vector<double> winter{-3, 1, 2};17    std::vector<double> nothing;18    std::cout << "冬天平均:" << average(winter) << '\n';19    std::cout << "沒有資料:" << average(nothing) << '\n';20    return 0;21}
輸出
冬天平均:0
沒有資料:0

兩個 0,一個是真的平均氣溫,一個是「根本沒有資料」,呼叫的人分不出來。而且就算分得出來,也得記著每次呼叫都檢查。C++ 的另一個辦法是異常(exception):出了錯,函式不返回,而是「丟擲」一個異常,交給知道怎麼處理的人。

throw 和 try / catch

main.cpp
1#include <iostream>2#include <stdexcept>3#include <vector>4 5double average(const std::vector<double>& temps) {6    if (temps.empty()) {7        throw std::runtime_error("沒有資料");8    }9    double total = 0;10    for (double t : temps) {11        total += t;12    }13    return total / temps.size();14}15 16int main() {17    std::vector<double> nothing;18    try {19        double avg = average(nothing);20        std::cout << "平均:" << avg << '\n';21    } catch (const std::runtime_error& e) {22        std::cout << "出錯了:" << e.what() << '\n';23    }24    std::cout << "程式繼續\n";25    return 0;26}
輸出
出錯了:沒有資料
程式繼續

三樣新東西:

  • throw std::runtime_error("沒有資料"); 建一個異常物件,把它丟擲。average 到這裡就不往下走了,也不回傳值。std::runtime_error 在 <stdexcept> 裡,括號裡是說明出了什麼錯的文字。
  • try { … } 圍住可能出錯的程式碼。
  • catch (const std::runtime_error& e) { … } 跟在 try 後面,接住這種異常。e.what() 取回當初寫的那段文字。

丟擲以後,try 裡剩下的語句全跳過,直接去 catch;catch 做完,程式從整個 try / catch 後面接著走。所以「平均:」那一行沒有顯示,「程式繼續」顯示了。

average 裡丟擲throw
跳過try 裡剩下的不做
catch 接住顯示 what()
接著往下走程式繼續
丟擲以後:try 裡剩下的全跳過,直接去 catch,做完再從 try / catch 後面接著走
猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <stdexcept>3 4int main() {5    try {6        std::cout << "1";7        throw std::runtime_error("x");8        std::cout << "2";9    } catch (const std::runtime_error& e) {10        std::cout << "3";11    }12    std::cout << "4\n";13    return 0;14}
練習 1

除數不能是 0

main 已經準備好接異常了,可 divide 碰到 0 不會丟擲。讓 divide 在 b 是 0 時丟擲 std::runtime_error,文字是 除數不能是 0。程式要顯示下面兩行。

要顯示
5
出錯了:除數不能是 0
exercise1.cpp
1#include <iostream>2#include <stdexcept>3#include <vector>4 5int divide(int a, int b) {6    return a / b;7}8 9int main() {10    std::vector<int> divisors{2, 0};11    for (int b : divisors) {12        try {13            std::cout << divide(10, b) << '\n';14        } catch (const std::runtime_error& e) {15            std::cout << "出錯了:" << e.what() << '\n';16        }17    }18    return 0;19}
輸出
點「執行」或按 Ctrl+Enter

沒接住會怎樣

要是沒有人接,異常一路往外傳,傳出了 main,程式就結束了:

main.cpp
1#include <iostream>2#include <stdexcept>3#include <vector>4 5double average(const std::vector<double>& temps) {6    if (temps.empty()) {7        throw std::runtime_error("沒有資料");8    }9    double total = 0;10    for (double t : temps) {11        total += t;12    }13    return total / temps.size();14}15 16int main() {17    std::vector<double> nothing;18    double avg = average(nothing);19    std::cout << "平均:" << avg << '\n';20    std::cout << "結束\n";21    return 0;22}
輸出
terminate called after throwing an instance of 'std::runtime_error'
  what():  沒有資料
Aborted (core dumped)

發生了什麼: 丟擲了一個 std::runtime_error,沒有 catch 接住它,程式就結束了(std::terminate)。

這三行和你在自己電腦上用 g++ 編出來的程式一樣:terminate called after throwing an instance of 'std::runtime_error' 說丟擲了一個 std::runtime_error 沒人接,於是呼叫了 std::terminate;what(): 後面是那段文字;Aborted (core dumped) 是程式被強行結束了。「結束」沒有顯示。

異常不能當作沒看見:要麼接住,要麼程式結束。這比回傳一個誰都可能忘了檢查的 0 好。

單選

一個異常沒有任何 catch 接住,一路傳出了 main。會怎樣?

標準庫自己會拋

第 11 課說過:v.at(5) 越界會丟擲 std::out_of_range,沒人處理就結束程式。第 5 課的 std::stoi 碰上不是數字的文字,也會丟擲 std::invalid_argument。現在你能接住它們了:

main.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4#include <vector>5 6int main() {7    std::vector<int> prices{12, 30, 8};8    try {9        std::cout << prices.at(5) << '\n';10    } catch (const std::exception& e) {11        std::cout << "下標不對:" << e.what() << '\n';12    }13    try {14        int n = std::stoi("十二");15        std::cout << n << '\n';16    } catch (const std::exception& e) {17        std::cout << "不是數字:" << e.what() << '\n';18    }19    std::cout << "兩個錯都接住了\n";20    return 0;21}
輸出
下標不對:vector::_M_range_check: __n (which is 5) >= this->size() (which is 3)
不是數字:stoi
兩個錯都接住了

這裡接的是 const std::exception&。std::exception 是標準庫所有異常的基類(第 23 課的繼承):std::runtime_error、std::out_of_range、std::invalid_argument 都是它的派生類,所以一個 catch (const std::exception& e) 全都接得住,e.what() 調到的是各自的版本(第 24 課的虛擬函式)。stoi 的 what() 很短,只有一個 stoi。

std::exception
std::runtime_error
std::logic_error
std::out_of_range
std::invalid_argument
  • std::exception
    • std::runtime_error
    • std::logic_error
      • std::out_of_range
      • std::invalid_argument
標準庫的異常是一棵繼承樹:接住 std::exception,整棵樹上的都接得住

按引用接(&):不復制,也不會把派生類物件切成基類物件;加 const,因為只是看看。這是接異常的老規矩。

單選

catch (const std::exception& e) 為什麼接得住 at() 丟擲的 std::out_of_range?

練習 2

接住越界的下標

第二次點單時下標是 7,menu.at(7) 會丟擲異常,程式結束。在迴圈體裡加上 try / catch,接住 std::out_of_range,顯示 沒有下標 7。程式要顯示下面兩行。

要顯示
紅茶
沒有下標 7
exercise2.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4#include <vector>5 6int main() {7    std::vector<std::string> menu{"咖啡", "紅茶", "果汁"};8    std::vector<int> picks{1, 7};9    for (int i : picks) {10        std::cout << menu.at(i) << '\n';11    }12    return 0;13}
輸出
點「執行」或按 Ctrl+Enter

幾個 catch

一個 try 後面可以跟好幾個 catch,按不同的錯做不同的事。丟擲時從上往下比,第一個對得上的接住,後面的不看:

main.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4#include <vector>5 6int seat_number(const std::string& text) {7    int n = std::stoi(text);8    if (n < 1 || n > 30) {9        throw std::runtime_error("沒有這個座位");10    }11    return n;12}13 14int main() {15    std::vector<std::string> tickets{"12", "abc", "45"};16    for (const auto& t : tickets) {17        try {18            int seat = seat_number(t);19            std::cout << "座位 " << seat << '\n';20        } catch (const std::invalid_argument& e) {21            std::cout << t << " 不是數字\n";22        } catch (const std::runtime_error& e) {23            std::cout << t << ":" << e.what() << '\n';24        }25    }26    return 0;27}
輸出
座位 12
abc 不是數字
45:沒有這個座位

"abc" 讓 stoi 丟擲 invalid_argument,第一個 catch 接住;"45" 讓 seat_number 自己丟擲 runtime_error(「沒有這個座位」是這個程式自己的規矩,用 runtime_error),第一個對不上,第二個接住。try 在迴圈體裡,所以一張票出錯,下一張照樣處理。

正因為第一個對上的就接住,具體的 catch 要寫在前面,std::exception 這種什麼都接的寫在最後。還有一個 catch (...),三個點,什麼型別都接,但拿不到 what(),只能放在最後一個。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <stdexcept>3 4void check(int n) {5    std::cout << "a";6    if (n > 2) {7        throw std::runtime_error("太大");8    }9    std::cout << "b";10}11 12int main() {13    try {14        check(1);15        check(5);16        check(2);17        std::cout << "c";18    } catch (const std::exception& e) {19        std::cout << "d";20    }21    std::cout << "e\n";22    return 0;23}
練習 3

修好它:具體的 catch 寫在前面

「八」不是數字,本該顯示 不是數字:八,可現在顯示的是 出錯了,編譯器還給了一個警告。只調整程式碼的順序,讓程式顯示下面兩行。

要顯示
16
不是數字:八
exercise3.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4#include <vector>5 6int main() {7    std::vector<std::string> inputs{"8", "八"};8    for (const auto& text : inputs) {9        try {10            int n = std::stoi(text);11            std::cout << n * 2 << '\n';12        } catch (const std::exception& e) {13            std::cout << "出錯了\n";14        } catch (const std::invalid_argument& e) {15            std::cout << "不是數字:" << text << '\n';16        }17    }18    return 0;19}
輸出
點「執行」或按 Ctrl+Enter

路上的物件會析構

異常從 throw 跳到 catch,中間可能隔著好幾層函式。這幾層裡的區域性物件怎麼辦?C++ 保證:一層一層退出時,每層的區域性物件都會析構,和函式正常結束時一樣。這叫堆疊展開。

main.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4 5class Cup {6public:7    Cup(const std::string& name) : name_(name) {8        std::cout << "拿出" << name_ << '\n';9    }10    ~Cup() {11        std::cout << "收起" << name_ << '\n';12    }13 14private:15    std::string name_;16};17 18void make_tea() {19    Cup cup{"茶杯"};20    throw std::runtime_error("水不夠");21    std::cout << "倒茶\n";22}23 24int main() {25    try {26        Cup tray{"托盤"};27        make_tea();28    } catch (const std::exception& e) {29        std::cout << "接住:" << e.what() << '\n';30    }31    return 0;32}
輸出
拿出托盤
拿出茶杯
收起茶杯
收起托盤
接住:水不夠

點單步,走到第 20 行的 throw 以後一步一步看:下一步不是 catch,而是 make_tea 裡 cup 的解構函式;再下一步,main 的 try 裡 tray 的解構函式;然後才到 catch。先收起茶杯、再收起托盤,和它們建出來的順序相反。

main():

異常往外跳的路上一層一層收拾:先析構 make_tea 裡的 cup,再析構 try 裡的 tray,最後才進 catch

所以第 21 課的智慧指標、第 11 課的 vector 碰上異常也不會洩漏:它們都是區域性物件,解構函式照樣執行。

猜輸出猜錯也沒關係

這段程式顯示什麼?

1#include <iostream>2#include <stdexcept>3 4class Note {5public:6    Note(int n) : n_(n) {}7    ~Note() {8        std::cout << n_;9    }10 11private:12    int n_;13};14 15void work() {16    Note b{2};17    throw std::runtime_error("x");18}19 20int main() {21    try {22        Note a{1};23        work();24    } catch (const std::exception& e) {25        std::cout << "c";26    }27    std::cout << '\n';28    return 0;29}

自己的異常類

標準的異常類夠用,但有時想讓異常多帶點東西,或者讓 catch 能分清「這是銀行的錯」。自己寫一個類,繼承 std::runtime_error 就行:

main.cpp
1#include <iostream>2#include <stdexcept>3#include <string>4 5class BankError : public std::runtime_error {6public:7    BankError(const std::string& message, int short_by)8        : std::runtime_error(message), short_by_(short_by) {}9    int short_by() const {10        return short_by_;11    }12 13private:14    int short_by_;15};16 17class Account {18public:19    Account(int balance) : balance_(balance) {}20    void withdraw(int amount) {21        if (amount > balance_) {22            throw BankError("餘額不足", amount - balance_);23        }24        balance_ -= amount;25        std::cout << "取出 " << amount << ",剩 " << balance_ << '\n';26    }27 28private:29    int balance_;30};31 32int main() {33    Account account{100};34    try {35        account.withdraw(30);36        account.withdraw(100);37    } catch (const BankError& e) {38        std::cout << e.what() << ",還差 " << e.short_by() << '\n';39    } catch (const std::exception& e) {40        std::cout << "別的錯:" << e.what() << '\n';41    }42    return 0;43}
輸出
取出 30,剩 70
餘額不足,還差 30

BankError 的建構函式在初始化列表裡呼叫基類的建構函式 std::runtime_error(message)(第 23 課),what() 就有了;自己再加一個成員 short_by_,記著差多少。因為它是 std::runtime_error 的派生類,別處只寫了 catch (const std::exception& e) 的程式碼也接得住它。

注意: throw 後面其實可以是任何值,throw 42;、throw std::string("錯了"); 都行。可是那樣就沒有 what(),catch (const std::exception&) 也接不住。習慣上只拋標準異常或它們的派生類。

單選

BankError 繼承了 std::runtime_error。丟擲一個 BankError,哪個 catch 接不住它?

什麼時候用異常

異常適合「這裡處理不了、也不該發生」的錯:函式做不成它答應的事,又不知道該怎麼辦,就交給呼叫它的人。建構函式是最典型的地方,它沒有回傳值,引數不對時只能丟擲,這樣就不會有一個半壞的物件:

main.cpp
1#include <iostream>2#include <stdexcept>3 4class Discount {5public:6    Discount(int percent) : percent_(percent) {7        if (percent < 0 || percent > 100) {8            throw std::invalid_argument("折扣要在 0 到 100 之間");9        }10    }11    double apply(double price) const {12        return price * (100 - percent_) / 100;13    }14 15private:16    int percent_;17};18 19int main() {20    try {21        Discount sale{20};22        std::cout << sale.apply(50) << '\n';23        Discount wrong{120};24        std::cout << wrong.apply(50) << '\n';25    } catch (const std::invalid_argument& e) {26        std::cout << e.what() << '\n';27    }28    return 0;29}
輸出
40
折扣要在 0 到 100 之間

wrong 根本沒建成,後面也就沒機會用到一個錯的折扣。

情況用什麼
很常見、呼叫的人馬上就要處理(找不到、輸入不對)回傳值,比如 find 返回 end()
少見、這裡處理不了(引數不對、資源沒有了)throw 異常
程式自己寫錯了(下標算錯)修程式碼,別靠 catch 掩蓋
單選

哪種情況最適合 throw 一個異常?

這一課學會了

  • 出了錯,函式可以 throw 一個異常,比如 throw std::runtime_error("沒有資料");(<stdexcept>),不用回傳一個容易弄混的特殊值。
  • try { … } 圍住可能出錯的程式碼,catch (const std::runtime_error& e) 接住,e.what() 是那段文字;接住以後從 try / catch 後面接著走。
  • 沒人接住,程式結束:terminate called after throwing an instance of …、what():、Aborted (core dumped)。
  • v.at() 和 std::stoi 自己會拋(out_of_range、invalid_argument),現在能接住了。
  • catch (const std::exception& e) 接住所有標準異常;幾個 catch 時第一個對上的接住,具體的寫在前面,catch (...) 放最後。
  • 丟擲以後,從 throw 到 catch 路上每一層的區域性物件都會析構(堆疊展開)。
  • 自己的異常類繼承 std::runtime_error,建構函式寫 : std::runtime_error(message)。
  • 少見、這裡處理不了的錯用異常;常見的情況用回傳值;程式寫錯了就修程式碼。
第 26 課學完了嗎?第 26 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 27 課 · 15 分鐘迭代器迭代器是指著容器裡一個元素的「手指」:begin 和 end、*it 取值、++it 往後走、map 的 it->first 和 it->second、邊走邊刪時 erase 返回下一個、範圍 for 背後的樣子。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。