今天我一直在处理异常处理问题。如果它处于void函数中,我已经想过要让它工作,但是如何处理必须返回值的函数。主要的最后3行是"问题"发生。我之前发现这个链接可以帮助我做到这一点,但我的异常处理必须全部包含在类结构中,所以我不能在main中尝试/ throw / catch。我想了解发生了什么。 [1]:What type of exception should I throw?
提前致谢。
#include <iostream>
#include <exception>
class out_of_range : public std::exception
{
private:
std::string msg;
public:
out_of_range(const std::string msg) : msg(msg){};
~out_of_range(){};
virtual const char * what()
{
return msg.c_str();
}
};
class divide
{
private:
int a;
int * _ptr;
public:
divide(int r): a(r), _ptr(new int[a]) {};
~divide(){ delete[] _ptr; };
int get(int index) const
{
try
{
if (index < 0 || index >= a)
throw out_of_range("Err");
else
return _ptr[index];
}
catch (out_of_range & msg)
{
std::cout << msg.what() << std::endl;
}
}
int &get(int index)
{
try
{
if (index < 0 || index >= a)
throw out_of_range("Err");
else
return _ptr[index];
}
catch (out_of_range & msg)
{
std::cout << msg.what() << std::endl;
}
}
};
int main()
{
divide test(6);
for (int i(0); i < 6; ++i)
{
test.get(i) = i * 3;
std::cout << test.get(i) << std::endl;
}
std::cout << "test.get(10): " << test.get(10) << std::endl;
test.get(3) = test.get(10);
std::cout << "test.get(3): " << test.get(3) << std::endl;
return 0;
}
答案 0 :(得分:2)
如果你在divide::get
方法中捕获异常,它必须以某种方式告诉其调用者出错的地方。所以实现可能看起来像这样:
class divide
{
//..
bool get(int nIndex, int* nResult);
//...
int main()
//...
int nRes = 0;
if(!test.get(10, &nRes))
cout << "Something is not right";
如果有很多事情可能会出错,您可以返回一些错误代码,而不是bool
。但是如果你使用这个方法,你的异常类中没有必要,你可以简单地返回错误而不会引发异常。