例外と契約
Coddyの「Ruby開発者のためのC++」コースのレッスン 28/48。
Rubyではraiseで例外オブジェクトを送出し、クラスに基づいてrescue節を選び、例外がスタックをさかのぼる間にensureコードを実行します。これが、ブロック付きのFile.openがファイルを閉じる仕組みです。C++にはensureもfinallyもありません。代わりに、C++のスタック巻き戻しではデストラクターが呼び出されます。C++では型付き例外を送出し、スタック巻き戻し中に構築済みの自動オブジェクトを破棄します。想定される例外の種類はconst参照で捕捉しましょう。
Ruby
def with_guard
yield
ensure
puts "released"
end
begin
with_guard { Integer("bad") }
rescue ArgumentError
puts "invalid"
end
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Guard{~Guard(){std::cout<<"released\n";}};
void require_name(const std::string& s){Guard g;if(s.empty())throw std::invalid_argument("name");}
int main(){
try{require_name("");}catch(const std::invalid_argument& e){std::cout<<"missing "<<e.what()<<"\n";}
}
各プログラムを個別に追ってください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースと出力先の出力が一致するとは限りません。
チャレンジ
簡単入力: 分子と除数。整数の商を返し、ゼロ方向に切り捨てます。除数がゼロの場合は std::invalid_argument をスローします。ドライバーはこれをキャッチして invalid を出力します。
exercise.hpp と exercise.cpp で宣言された API を実装してください。両方のファイルを編集できます。公開シグネチャは変更しないでください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、指定されている箇所では公開 API の動作も個別に確認します。API 内で出力せず、戻り値を返してください。整数の入力値と結果は符号付き int の範囲内です。特に指定がない限り、テキストは ASCII です。
自分で試してみよう
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;try{std::cout<<divide(a,b)<<"\n";}catch(const std::invalid_argument&){std::cout<<"invalid\n";}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Ruby開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ