0
#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() 中为所有这些函数编写一个通用的全部捕获?我在想假设每个函数都返回不同的数据类型,并相应地打印一条语句。

4

1 回答 1

1

我在想假设每个函数都返回不同的数据类型

如果您的意思是“会抛出不同的数据类型”,那么您可以考虑一个模板函数来完成打印工作。

template<typename T>
void printException(T exept) {
     std::cerr << exept << std::endl;
}

为了获得更好的效果(因为可能会错误地传递 std::cerr 由于多种原因无法打印的东西),您可以简单地使用 std::exception 并在构造异常对象时向其传递一条消息,以便当您捕获它时可以简单地做:

void printException(const std::exception& e)  {
    // print some information message if needed then...
    std::cerr << e.what() << std::endl;
}

有没有办法为所有这些函数编写一个通用的 catch 全部可能在 main() 中?

是的,您只需删除每个函数中的所有 catch 语句,并在包含所有“有风险的方法”的 try 块之后将一个放在 main 中 - 不是它们有风险,而是它们可以抛出异常。这是一个例子:

int main(int argc, char** argv) {
    try {
        riskyMethod1();
        riskyMethod2();
        riskyMethod3();
    }
    catch (const std::exception& e) {
        printException(e);
    }
    return 0;
}

为了实现这一点,我再次建议放弃抛出字符串以使异常对象受益。您可以使用 division_with_one_exeption、multiplying_with_one_exception 仅举几例(这是一个建议,因为您可以轻松使用 std::exception,并为其提供异常消息)。

于 2018-03-24T06:01:05.613 回答