C++类包含异常处理

C++ Class Contained Exception Handling

本文关键字:异常处理 包含 C++      更新时间:2023-10-16

我今天已经使用异常处理很长时间了。 我已经想出如果它在 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;
}

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