Menu
CoddyTech

例外と契約

Coddyの「Python開発者のためのC++」コースのレッスン 28/48。

Pythonのtry/exceptは例外オブジェクトを処理し、withはリソースを管理します。C++ではスタックの巻き戻しによってデストラクターが呼び出されます。C++は型付き例外をスローし、スタックの巻き戻し中に構築済みの自動オブジェクトを破棄します。想定される例外カテゴリをconst参照で捕捉します。

Python

class Guard:
    def __enter__(self):
        return self
    def __exit__(self, kind, value, trace):
        print("released")
try:
    with Guard():
        int("bad")
except ValueError:
    print("invalid")

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
void require_name(const std::string& s){if(s.empty())throw std::invalid_argument("name");}
int main(){
try{require_name("");}catch(const std::invalid_argument&){std::cout<<"missing\n";}
}

各プログラムを個別にトレースしてください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースと出力先が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力: 分子と除数。整数の商を返し、ゼロ方向に切り捨てます。除数がゼロの場合は 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";}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Python開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ