C++ c+;中深度嵌套函数的单个catch-all语句+;? #包括 使用名称空间std; 空减法(整数a,整数b){ 试一试{ 如果(b==1) 抛出“上一个数字减去1的结果”; 库特
我想假设每个函数返回不同的数据类型 如果您的意思是“将抛出不同的数据类型”,那么您可以考虑使用一个模板函数来完成打印工作C++ c+;中深度嵌套函数的单个catch-all语句+;? #包括 使用名称空间std; 空减法(整数a,整数b){ 试一试{ 如果(b==1) 抛出“上一个数字减去1的结果”; 库特,c++,exception-handling,try-catch,nested-function,catch-all,C++,Exception Handling,Try Catch,Nested Function,Catch All,我想假设每个函数返回不同的数据类型 如果您的意思是“将抛出不同的数据类型”,那么您可以考虑使用一个模板函数来完成打印工作 #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<
#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;
}
为了实现这一点,我再次建议删除抛出字符串,以利于异常对象。您可以将_除以_one_exeption,将_乘以_one_exception,仅举几个例子(这是一个建议,因为您可以轻松使用std::exception,将异常消息提供给它)“我必须为每个函数分别键入catch语句"为什么?解决办法不是这样。这就是为什么我想知道是否有办法将所有catch语句组合到一个catch all blockWell中,不要在抛出后立即捕获。如果要这样做,抛出是没有意义的。但它需要每个单独的函数都有一个catch语句?所以add functi中不会有异常吗需要其他的函数。你需要在C++上找到一个好的教程,它解释了异常的用法。
template<typename T>
void printException(T exept) {
std::cerr << exept << std::endl;
}
void printException(const std::exception& e) {
// print some information message if needed then...
std::cerr << e.what() << std::endl;
}
int main(int argc, char** argv) {
try {
riskyMethod1();
riskyMethod2();
riskyMethod3();
}
catch (const std::exception& e) {
printException(e);
}
return 0;
}