C++;嵌套方法try-catch(实践) 我是C++的新成员(来自C),编写了一个类 b>代码>,它是另一个类的代码< 。p>

C++;嵌套方法try-catch(实践) 我是C++的新成员(来自C),编写了一个类 b>代码>,它是另一个类的代码< 。p>,c++,c++11,exception,C++,C++11,Exception,如果父级尝试从B的容器访问不存在的数据,成员B将抛出异常(我抛出无效的\u参数异常)。成员B有一个对象,可以将其视为类似于STL容器,因此在本例中就是这样 我的问题是:如果我在 < 中捕获了原始的无效参数异常,那么认为重新C++抛出相同的异常(我将重新抛出原始错误,但是我在其中进行一些日志记录,所以什么)(代码)>是不同的,还是我可以直接抛出 STD::异常< /代码>。我的代码现在有很多 try{A.calls\u b\u exception}catch(std::invalid\u参数&ie

如果父级尝试从
B
的容器访问不存在的数据,成员
B
将抛出异常(我抛出
无效的\u参数
异常)。成员
B
有一个对象,可以将其视为类似于STL容器,因此在本例中就是这样

我的问题是:如果我在<代码> < <代码>中捕获了原始的无效参数异常,那么认为重新C++抛出相同的异常(我将重新抛出原始错误,但是我在其中进行一些日志记录,所以<代码>什么)(代码)>是不同的,还是我可以直接抛出<代码> STD::异常< /代码>。我的代码现在有很多

try{A.calls\u b\u exception}catch(std::invalid\u参数&ie){…}catch(std::exception&e){…}

我想知道我是否可以把它们减少到

try{A.calls\u b_exception}catch(std::exception&e){…}

仍然遵循良好的C++范例。 与我的情况类似的示例代码:

class B
{
    std::vector<int> stuff;

    int get_value(int index)
    {
       if (index >= stuff.size()) {
            stringstream err;
            err << "--> invalid index " << index << " for stuff";
            throw std::invalid_argument(err.str());
        }
    }
}

class A
{
    B b;
    // Assume there are methods to add a bunch of stuff to B
    int get_value(int index) 
    {
        try {
            b.get_value();
        } catch (std::invalid_argument& ie) {
            stringstream err;
            err << ie.what() << "\n\t--> A::get_value(" << index << ")";
            // should I throw the same exception here or is this considered good C++ etiquette?
            throw std::exception(err.str());
        } catch (std::exception& e) {
            throw;    // something I was not anticipating handling happened
        }
    }
}

int main
{
    A a;
    // Assume more stuff to add to A
    try {
        a.get_value(-1);
    }
    catch (std::exception& e) {
        stringstream err;
        err << "--> invalid index " << index << " for main";
        throw std::exception(err.str());exception here?
    }
}
B类
{
std::载体材料;
int get_值(int索引)
{
如果(索引>=stuff.size()){
弦乐;

err您无法实例化
std::exception(std::string)
,因此我的初始方法将不起作用。
感谢大家花时间通读我的问题并帮助我解决问题。

打字错误?您的“我做这个”和“我应该做这个”是完全相同的。在顶级异常处理程序中,您实际上不知道异常来自何处或可能是什么,除非
try
块中的代码非常窄(比如您的单个函数调用)。我个人也不会捕获异常,除非我实际处理了错误,只是用更详细的错误消息重新引用它并不是在“处理”错误,依我看。
我的代码现在有很多:try{a.calls\u b_exception}catch(std::invalid_argument&ie){…}catch(std::exception&e){…}
。如果只记录它们,实际上不必捕获它们。
std::invalid_参数
继承自
std::exception
。捕获
std::exception
也将捕获
std::invalid_参数
,您仍然可以访问what()函数。
尝试{A.calls__b_exception}catch(std::exception&e){…}
很好。@JoachimPileborg:我最终通过终止并打印错误来处理错误。为了简洁起见,我在本例中没有这样做,因为我更关心的主题是,只要用户在运行时知道原因,抛出更一般的异常是否是好的做法。我的try块很窄,所以除了我预计会出现不可预测的系统异常,这也会导致程序提示退出。@user1810087:我知道继承,但我不确定是否最好在a中捕获特定异常,并在a中捕获更一般的异常,以及其他可能的异常(我将在编辑中添加)。