2016/5/27 1004. 简单减法

来源:互联网 发布:数据黑产吧 编辑:程序博客网 时间:2024/06/05 22:48

 和之前的几道题类似,只要在test里try 去调用calc,并catch 它throw出来的异常就好了。这里需要注意的是在函数名后加throw(类型)表示告诉try语句这个函数语句块里throw出来的只会是这种类型的错误。所以如果加的是throw(),就相当于是保证不会出错,不可能throw出错误来了。

#include <iostream>#include<stdexcept>using namespace std;int calc(int a, int b) throw(logic_error){if (a<0) throw out_of_range("Out of range exeception");else if (b<0) throw out_of_range("Out of range exeception");else if (a<b) throw logic_error("Minuend smaller than subtrahend");return a - b;}void test(int a, int b){try{cout << calc(a, b) << endl;}catch (logic_error ex){cout << ex.what() << endl;}}void f(){test(3, 1);test(-3, 1);test(1, -3);test(1, 3);}int main(){f();return 0;}


0 0