TriHard8
TriHard8

Reputation: 592

C++ Class Contained Exception Handling

I've been working with exception handling for a long while today. I've figured out to get it to work if it's in a void function, but how do I handle functions that have to return a value. The last 3 lines in main are where the "issue" happens. I found this link earlier to help me get this far, but my exception handling has to all be contained inside the class structure, so I can't have try/throw/catch in main. I'd like to understand what's going on. [1]: What type of exception should I throw?

Thanks in advance.

#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;
}

Upvotes: 0

Views: 67

Answers (1)

Ari0nhh
Ari0nhh

Reputation: 5920

If you catch exception in the divide::get method, it must somehow tell its caller that something went wrong. So implementation may look something like that:

class divide
{   
//.. 
    bool get(int nIndex, int* nResult);
//...
int main() 
//...
    int nRes = 0;
    if(!test.get(10, &nRes))
      cout << "Something is not right";

If there is many things that could go amiss, you could return some error code instead of bool. But if you use this method, there is no need in your exception class, you could simply return error without raising exception at all.

Upvotes: 2

Related Questions