例外でエラーを知らせる
まず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; }