C++ C++;类包含异常处理

C++ C++;类包含异常处理,c++,C++,今天我在异常处理方面工作了很长时间。如果它在一个void函数中,我已经找到了让它工作的方法,但是如何处理必须返回值的函数呢。main中的最后3行是“问题”发生的地方。我在前面找到了这个链接来帮助我做到这一点,但是我的异常处理必须全部包含在类结构中,所以我不能在main中使用try/throw/catch。我想知道发生了什么事。[1] : 提前谢谢 #include <iostream> #include <exception> class out_of_range :

今天我在异常处理方面工作了很长时间。如果它在一个void函数中,我已经找到了让它工作的方法,但是如何处理必须返回值的函数呢。main中的最后3行是“问题”发生的地方。我在前面找到了这个链接来帮助我做到这一点,但是我的异常处理必须全部包含在类结构中,所以我不能在main中使用try/throw/catch。我想知道发生了什么事。[1] :

提前谢谢

#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;
}
#包括
#包括
类超出范围:公共标准::异常
{
私人:
std::字符串msg;
公众:
超出范围(const std::string msg):msg(msg){};
~out_of_range(){};
虚拟常量字符*what()
{
返回msg.c_str();
}
};
阶级划分
{
私人:
INTA;
int*\u ptr;
公众:
除法(intr):a(r),ptr(新的int[a]){;
~divide(){delete[]\u ptr;};
int get(int索引)常量
{
尝试
{       
如果(索引<0 | |索引>=a)
抛出超出范围(“错误”);
其他的
返回_ptr[索引];
}
捕获(超出范围和消息)
{

std::cout如果您在
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-get(int-nIndex,int*nResult);
//...
int main()
//...
int nRes=0;
如果(!测试获取(10,&nRes))
库特