【发布时间】:2013-02-10 09:45:04
【问题描述】:
我的问题是我正在编写一个应该在未来可读的程序,并且该程序有很多异常情况。所以每当我必须抛出异常时,我必须编写超过 10 行来初始化我的异常类并将程序中的信息附加到它。例如如下:
MyExceptionClass ex;
ex.setErrorMessage("PIN_CANNOT_GO_IN");
ex.setErrorDetails("The pin is asked to go to the state IN while the depth of the r-coordinate does not support it");
ex.setResolutionMessage("Configure your coordinates-file to move first to the correct position before changing the state of the pin");
ex.VariableList().resize(5);
ex.VariableList()[0].push_back("Pin state: ");
ex.VariableList()[0].push_back(ToString(pin.getPinState()));
ex.VariableList()[1].push_back("Pin target state: ");
ex.VariableList()[1].push_back(ToString(coordinatesData[coordinatesIndex].targetPinState));
ex.VariableList()[2].push_back("Current r Value: ");
ex.VariableList()[2].push_back(ToString(EncoderPosition.r));
ex.VariableList()[3].push_back("Current phi Value: ");
ex.VariableList()[3].push_back(ToString(EncoderPosition.phi));
ex.VariableList()[4].push_back("Current z Value: ");
ex.VariableList()[4].push_back(ToString(EncoderPosition.z));
ex.printLog();
ex.writeLog(exceptionLogFilePath.getValue());
throw ex;
所以只有 5 个变量,我必须写下所有这些...... 有没有一种有效的方法来包含程序中的所有信息(至少是变量),而不是每次我想抛出异常时都重写所有这些信息?
提前致谢。
【问题讨论】:
-
首先,用构造函数构造对象,而不是一堆setter。这就是构造函数的用途。其次,无论如何,你的例外是一堆字符串,只需将它们格式化为一个大的用户可呈现的大字符串并触发。
-
您是否尝试过编写一个生成异常的函数(即,包含除
throw行之外的所有内容),并且只执行throw exceptionGenerator()或者您如何调用该函数? -
函数如何访问我程序中的变量列表?这意味着我将不得不通过参数传递它们,然后我们回到第一方。有没有办法自动将所有变量添加到我的异常类中?
标签: c++ exception coding-style readability throw