#include<bits/stdc++.h>
using namespace std;
void subtract(int a,int b){
try{
if(b==1)
throw "Subtracting by 1 results in previous number";
cout<<a-b<<endl;
}
catch(const char *e){
cerr<<e<<endl;
}
};
void add(int a,int b){
try{
if(b==1)
throw "Adding with 1 results in next number";
}
catch(const char *e){
cerr<<e<<endl;
subtract(a+b,b);
}
};
void multiply(int a,int b){
try{
if(b==1)
throw "Multiplying with 1 has no effect!";
}
catch(const char *e){
cerr<<e<<endl;
add(a*b,b);
}
};
void divide(int a,int b){
try{
if(b==1)
throw "Dividing with one has no effect!";
}
catch(const char *e){
cerr<<e<<endl;
multiply(a/b,b);
}
};
void bodmas(int a,int b){
divide(a,b);
};
int main(){
int a,b;
cin>>a>>b;
bodmas(a,b);
return 0;
}
所以我试图通过编写一个小程序来理解深度嵌套函数以及异常处理的概念。但是在这个函数中,我必须为每个函数分别输入 catch 语句。有没有办法在 main() 中为所有这些函数编写一个通用的全部捕获?我在想假设每个函数都返回不同的数据类型,并相应地打印一条语句。