Search code examples
c++exceptionthrow

Cannot Exit Method after throwing Exception


Be warned, I don't really understand how throw works. Right now I have a method that checks if one variable is greater than or equal to another variable and if it isn't then it throws a string exception.

The problem is I don't know how to exit out of the method after the exception is thrown without getting an unhandled exception error.

CircleSquare Square::operator+ (const Circle& op2)
{
    /// Variables
    CircleSquare ret;

    /// Sets the temporary Square object's characteristics to LHS's colour, the sum of LHS sideLength + RHS sideLength, and Square name
    ret.SetName((char *)"Square-Circle");
    ret.SetColour((char *)this->GetColour());

    if (sideLength >= (op2.GetRadius() * 2))
    {
        ret.SetSideLength(sideLength);
    }
    else
    {
        throw ("The sideLength of square is smaller than the diameter of the contained circle.");
        return ret; // <--- Here is where the error occurs
    }

    if ((op2.GetRadius() * 2) <= sideLength && op2.GetRadius() >= 0.0)
    {
        ret.SetRadius(op2.GetRadius());
    }
    else
    {
        throw ("The radius of contained circle is larger than the sideLength of the square.");
        return ret;
    }

    return ret;
}

What I want it to do is to throw the exception and then I exit out of the method and handle the exception in my try-catch block, but instead, it comes up with the "Unhandled Exception" at the return ret;

How can I exit out of this method without getting the error?


Solution

  • You need to catch what you're throwing. Also, the return statement never happends when you throw. (You should delete the line that says:

    return ret; // <--- Here is where the error occurs
    

    Most likely, you'll see some warning of the compiler about that (that's code that is never going to be executed). Your code should compile without warings. Always. (-Werror compile flag is very good for this).

    throw means: return but not the normal way

    You need to do something like:

    try {
        Square a;
        Circle b;
        CircleSquare sum= a + b; // You try to sum
        // If you can, the return statement will give a value to sum
        // If you throw, sum will not get constructed, 
        // b and a will be destroyed and the catch 
        // will be executed instead of anything below
        // the call to operator+
        std::cout << "Sum is: " << sum << std::endl;
    } catch (std::string s) {
        // Will only catch exceptions of type std::string
        std::cerr << "Error: " << s << std::endl;
    }
    

    It is "like" if you did a goto to the catch block, but cleaning everything.

    If you don't handle it, it will still terminate every function abnormally until it finds a catch block of the right type or until it exites main.