c ++在try和catch时返回值

Ism*_*ush 1 c++ exception try-catch return-value

嗨,当警告"控制到达无效功能的结束"时,我该怎么办?我的重载运算符已尝试捕获并returns *this ;在try范围内.

我正在使用Eclipse,G ++是编译器,UBUNTU是linux

NNmatrix & operator*=(const NNmatrix<T> &mtrxB)
        {
            // A=2*3 B=3*4  return C=2*4
            const UINT aRows = this->size1();
            const UINT aCols = this->size2();
            const UINT bRows = mtrxB.size1();
            const UINT bCols = mtrxB.size2();
            try
            {
                // if cols of first(this) matrix == rows of second matrix
                if (aCols != bRows) throw bad_alloc();
                const UINT cRows = aRows;// = rows of first matrix
                const UINT cCols = bCols; // = cols of second matrix
                NNmatrix mtrxC(cRows, cCols);
                T val;
                for (UINT i = 0; i < cRows; i++)
                {
                    for (UINT j = 0; j < cCols; j++)
                    {
                        val = 0;
                        for (UINT k = 0; k < bRows; k++)
                        {
                            val += this->matrix.at(i).at(k) * mtrxB.getElement(k, j);
                        }
                        mtrxC.setElement(i, j, val);
                    }
                }
                *this = mtrxC;
                mtrxC.clear();
                return *this;
            }
            catch (exception& e)
            {
                cout<<"Dimension don't match: ("<<aRows<<","<<aCols<<") ("<<bRows<<","<<bCols<<")"<<endl;
            }
        }
Run Code Online (Sandbox Code Playgroud)

Ste*_*end 8

如果函数返回任何内容,则需要确保所有代码路径都返回一个值void.

如果你在没有重新抛出的情况下在内部处理这个函数的异常,为什么不是return *this;无条件地在函数的末尾,而不是从try块内部?

编辑:在下面的@ Mark的评论中,只需移动return语句就会隐藏在请求的操作的上下文中致命的错误,并使该库在此过程中相当不可靠.最好传播异常,如果这就是你将如何处理就地乘法错误(这似乎是一种合理的方法).