【发布时间】:2014-12-03 03:39:27
【问题描述】:
今天我从事异常处理已经有很长一段时间了。如果它在 void 函数中,我已经想办法让它工作,但是我如何处理必须返回值的函数。 main 中的最后 3 行是“问题”发生的地方。我之前找到了这个链接来帮助我做到这一点,但是我的异常处理必须全部包含在类结构中,所以我不能在 main.catch 中使用 try/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;
}
【问题讨论】:
标签: c++