【问题标题】:C++ Class Contained Exception HandlingC++ 类包含的异常处理
【发布时间】: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++


    【解决方案1】:

    如果你在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。但是如果你使用这个方法,你的异常类就不需要了,你可以简单地返回错误而不引发异常。

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多