这是上周测试的(修改后的)问题。 我得到了一个带有预定义数字的异常类:
class ErrorException {
/**
* Stub class.
*/
private :static long ErrorCode;
public: ErrorException( string str) {
cout <<str;
}
};
long ErrorException::ErrorCode = -444;
我想我应该做的是捕获异常然后将数字作为错误代码返回,但我不知道如何获取数字。我可以让捕获返回一个字符串而不是数字作为字符串:
#include "stdafx.h"
#include <iostream>
#include "ErrorException.h"
#include "errno.h""
#include <string>;
class FillerFunction {
public :
virtual int getFillerFunction(int x) throw (ErrorException) = 0;
} // this notation means getFillerFunction is always throwing ErrorException?
double calculateNumber(int y){
//.....
try{
if (y !=0){
throw(ErrorException(?????))
}
};
double catchError(){
catch(ErrorException& x);
};
我最终让它返回字符串“error”,这并不比使用 if 语句好。我已经在 C++ 和动态异常中查找了其他捕获抛出示例,但我找不到一个异常获取类中定义的变量的示例。如何访问 ErrorCode,保存更改 ErrorException 的返回类型( )?
最佳答案
虽然这个问题已经得到解答,但我只想添加一些关于在 C++11 中正确处理异常的注意事项:
首先,不应使用 throw(ErrorException)
,因为它已被弃用:http://en.cppreference.com/w/cpp/language/except_spec
此外,通常建议利用 C++ 提供标准异常类这一事实,我个人通常从 std::runtime_error
派生。 .
为了真正利用C++11中的异常机制,我推荐使用std::nested_exception
和 std::throw_with_nested
如 StackOverflow 所述 here和 here .创建适当的异常处理程序将允许您在代码中获取异常的回溯,而无需调试器或繁琐的日志记录。由于您可以使用派生的异常类来执行此操作,因此您可以向此类回溯添加大量信息!
你也可以看看我的MWE on GitHub ,回溯看起来像这样:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
关于c++ - 在 C++ 中将类变量传递给异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39069398/