例外と契約
Coddyの「C#開発者のためのC++」コースのレッスン 28/48。
C#の例外は検査されず、finallyはクリーンアップをサポートします。C++ではデストラクタを使ってスコープに束縛されたリソースをクリーンアップします。C++は型付き例外をスローし、スタックの巻き戻し中に構築済みの自動オブジェクトを破棄します。想定される例外カテゴリはconst参照で捕捉します。
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
try { throw new ArgumentException("bad"); } catch(ArgumentException error) { Console.WriteLine(error.Message); }
}
}
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";}
}
各プログラムを個別に追跡してください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースとターゲットの出力が一致するとは限りません。
チャレンジ
簡単入力:分子と除数。整数の商を返し、ゼロ方向に切り捨てます。除数がゼロの場合は 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";}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
C#開発者のためのC++のすべてのレッスン
自分で練習してみよう: C++オンラインコンパイラ