这是上周一次考试中的一个(修改的)问题。我得到了一个异常类,其中包含一个预定义的数字:
class ErrorException {
/**
* Stub class.
*/
private :static long ErrorCode;
public: ErrorException( string str) {
cout <<str;
}
};
long ErrorException::ErrorCode = -444;我想我应该做的是捕捉异常,然后将数字作为错误代码返回,但是我想不出如何获得这个数字。我可以让捕获返回一个字符串,但不能将数字返回为string:
#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++和动态异常中查找了其他捕获抛出示例,但是我找不到一个异常获取class.How中定义的变量的示例,我是否访问了ErrorCode,保存了更改ErrorException()的返回类型?
发布于 2016-08-21 22:52:33
在抛出过程中,您正在构造一个异常对象。如果您希望传递一个数字,则必须提供适当的构造函数。
快速和肮脏:
class ErrorException {
private :
static long ErrorCode;
public:
ErrorException( string str) {
cerr <<str<<endl;
}
ErrorException( long mynumeric code) {
cerr <<"error "<<mynumericcode<<endl;
}
};抓捕应如下所示:
double calculateNumber(int y){
try {
if (y !=0){
throw(ErrorException(227));
}
} catch(ErrorException& x) {
cout << "Error catched"<<endl;
}
}必须进一步阐述
在异常构造函数中打印某些内容是不寻常的。您最好填充捕获中所需的信息,以便以后可以使用适当的getter访问这些信息。然后,将在异常处理程序中进行打印。
如果您有一个静态错误代码,我假设某个地方有一个函数,它返回最后一个错误代码,不管发生了什么。因此,您可能会更新这段代码(但是您打算如何使用现有的字符串替代方案来更新它呢?
在这里,它会是什么样子:
class ErrorException {
private :
static long LastErrorCode;
long ErrorCode;
string ErrorMessage;
public:
ErrorException(long ec, string str) : ErrorCode(ec), ErrorMessage(str)
{
LastErrorCode = ec;
}
static long getLastError() const { return LastErrorCode; } // would never be reset
long getError() const { return ErrorCode; }
string getMessage() const { return ErrorMessage; }
};抓捕应如下所示:
double calculateNumber(int y){
try {
if (y !=0){
throw(ErrorException(227,"y is not 0"));
}
} catch(ErrorException& x) {
cerr << "Error "<<x.getError()<<" : "<<x.getMesssage()<<endl;
}
cout << "Last error ever generated, if any: " << ErrorException::getLastErrror()<<endl;
}无论如何,我建议你在重新发明方向盘之前先看看std::exception。
发布于 2017-10-26 08:08:40
虽然这个问题已经得到了回答,但我只想在C++11中添加一些关于正确异常处理的说明:
首先,不应该使用throw(ErrorException),因为它被废弃了:等级库
此外,通常建议使用C++提供标准异常类的事实,我个人通常是从std::runtime_error派生的。
为了真正利用C++11中的异常机制,我建议使用std::nested_exception和std::throw_with_nested,如StackOverflow 这里和这里所描述的那样。创建适当的异常处理程序将允许您对代码中的异常()进行回溯跟踪(),而无需调试器或繁琐的日志记录。因为您可以使用派生的异常类来完成这个任务,所以您可以向这种回溯中添加很多信息!您还可以查看我的GitHub上的MWE,其中回溯跟踪看起来如下所示:
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"https://stackoverflow.com/questions/39069398
复制相似问题