上級 › terminate called after throwing an instance of '...' の原因と直し方 › パターン3
terminate called after throwing an instance of '...' の原因と直し方
throwで投げた例外をどこのtry-catchでも捕まえられず、プログラム全体が異常終了してしまうバグです。
1 #include <iostream> 2 #include <stdexcept> 3 void checkStock(int stock, int order) { 4 if (order > stock) { 5 throw std::runtime_error("out of stock"); 6 } 7 std::cout << "shipped" << std::endl; 8 } 9 int main() { 10 checkStock(3, __); ^ 11 return 0; 12 }
terminate called after throwing an instance of 'std::runtime_error'
what(): out of stock
Aborted
空欄を埋めてコンパイル・実行を通す
例外の中身(what()で得られるメッセージ)はプログラマが自由に決められますが、捕まえられなければ結局terminateで強制終了する点は変わりません。
次の問題