c++ try and catch 时的返回值

标签 c++ exception return-value try-catch

您好,当警告“控制到达非无效函数的末尾”时,我该怎么办? 我的重载运算符有 try 和 catch 并且 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;
            }
        }

最佳答案

如果函数返回除 void 之外的任何内容,您需要确保所有代码路径都返回一个值。

如果您在该函数内部处理异常而不重新抛出,为什么不在函数末尾无条件地返回 return *this;,而不是从 try 中返回阻止?

编辑:根据下面@Mark 的评论,简单地移动 return 语句会隐藏在所请求操作的上下文中的 fatal error ,并使库在该过程中相当不可靠。最好传播异常,如果这是您要处理就地乘法错误的方式(这似乎是一种合理的方法)。

关于c++ try and catch 时的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4247606/

相关文章:

c++ - 使用 SDL2 和 OpenGL 使用 SDL TTF 显示文本

c++ - 与嵌套邻居形成邻接表的算法

c# - PowerShell 参数绑定(bind)异常

java - 使一组函数全部返回唯一值而无需硬编码数字?

c# - 是否值得使用值元组作为返回值来包含成功标志?

c++ - 如何处理构造函数中的错误值?

c++ - 在 C 或 C++ 中的空行后开始打印

C++ Boost::ASIO 线程池问题

Java 网络问题 : java.net.ConnectException:连接被拒绝:连接

python - 在 python 中获取异常类名?