例外でエラーを知らせる

まずtryブロックを実行してみて、異常系の処理だった場合はthrowで投げてcatchブロックで捕まえる。noexcept(false)を一往つけたが下の例では不要。

#include <iostream>
#include <string>
using namespace std;

double divi(double a, double b) noexcept(false) {
//double divi(double a, double b) throw(string) {

    // 異常系の処理
    if (b == 0) {
        throw string("0で除算されました。");
    }
    // 正常系の処理
    else {
        return a / b;
    }
}

int main() {
    double ans;

    for (int i = -3; i < 4; i++) {
        try {
            ans = divi(1, i);
            cout << ans << endl;
        }
        catch (string message) {
            cout << message << endl;
        }
    }

    return 0;
}

f:id:ti-nspire:20190517062022p:plain