In C and C++ you can return a single variable inside a function. Now in the case
ID: 654981 • Letter: I
Question
In C and C++ you can return a single variable inside a function. Now in the case that variable is returning data, and not an error code, you can use exceptions. But how is that possible? If you data being returned is the data you tell your function to return, then there is practically no way for the function calling it to know it's success (because the return is used for data, and not an error code). Also, the ability for a exception to literally stop the function in the middle of the code to return the error. How do C++ compilers achieve this?
Explanation / Answer
When a function throws an exception it does not return a value of the type specified by the function specification, and it doesn't return to the point where the function was called. It instead "returns" an exception object, and it "returns" that object to whatever catch block that catches that particular kind of exception.
That I put "returns" in quotes is intentional. It's best not to think of throw as returning a value. It instead throws a value to the catch block that handles the exception. The mechanism for handling normal function call and return is almost always implemented in the form of a call stack.
Exception handling works by a different mechanism than the call stack, but that exception handling mechanism has to do so in a manner consistent with the call stack. The catch block that catches a thrown exception might be several calls above the function that called the function that threw the exception. All of the intervening stuff, the temporary variables passed as arguments to and the local variables declared in those intervening functions, has to be cleaned up along the way. This is called "unwinding the stack".