加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C中以干净的方式处理异常

发布时间:2020-12-16 09:42:30 所属栏目:百科 来源:网络整理
导读:我的问题是我正在编写一个应该对未来可读的程序,并且该程序有很多异常情况.因此,每当我必须抛出异常时,我必须编写超过10行来初始化我的异常类并将程序中的信息附加到它.例如如下: MyExceptionClass ex;ex.setErrorMessage("PIN_CANNOT_GO_IN");ex.setErrorD
我的问题是我正在编写一个应该对未来可读的程序,并且该程序有很多异常情况.因此,每当我必须抛出异常时,我必须编写超过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个变量,我不得不写下所有…
是否有一种有效的方法来包含程序中的所有信息(至少是变量)??,并且每次我想抛出异常时都不会重写所有这些信息?

提前致谢.

解决方法

您可以使用一个公共函数(fill_out_exception_parameters)填充VariableList对象以获取一般异常,并在您编写的任何新异常类中重用它

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读