Reputation: 1968
I am just asking a general quesion which arised out of curiosity when I was working on one of the library project where in another method throws exception insead of return value but I want to convert that exception to return value. I solved it using multiple try catch blocks but just want to know is there a way in C++ to resume after an exception has been thrown.
Upvotes: 3
Views: 778
Reputation: 20759
To have a resume
instruction that works safely, it should jump not just after the throw
, but just before the if
that precede it, in order to re-test the condition.
The problem, here, is that by the way C++ exception are conceived they are statement themselves and are not necessarily immediate condition branches. (if
and throw
are defined each other independently)
Also, between the throw
and the catch
(that may be several function calls outside) there is a thing named "stack unrolling" that actually calls all the desctructors of everything local is left into the blocks that have to be escaped out. A "resume
" should reconstruct all those objects, but since the action of such destructors does not depend on the throw instruction itself, and may be are not "reversible", is mostly impossible to restore the system state consistently.
A possible idiom can be
for(;;)
{
try
{
... everything may throw ...
break; //if you are here everything was successful, so stop looping and go on
}
catch(whatever_you_may)
{
try_to_repair;
if(impossible) throw;
}
}
practically you loop until you succeed or decide it is not anymore the case.
But note how this is a re-execution, and not a re-construction (or un-destruction)
Upvotes: 0
Reputation: 154047
I'm not completely sure what you want. Converting an exception into a return code is not resuming after the exception. The C++ committee considered resuming, but it wasn't clear what that might mean. Consider:
int
someFunction()
{
// ...
if ( someCondition ) {
throw SomeException();
}
assert( !someCondition );
// ...
}
In C++, the assert
can never trigger (and one wouldn't
normally write it, since the if
and the throw
make it clear
that the asserted condition is valid afterwards). If you could
resume the exception, the assert
would (or at least might)
trigger; you'd loose an important means of code validation.
Also people who had used it in other languages reported that it didn't actually work well, and that in every case where they'd started using resumption, they'd had to change the code to not use it later.
Upvotes: 6
Reputation: 180235
No. In fact, the compiler may not even emit instructions for unreachable code after an exception is thrown:
throw std::invalid_argument;
int i = 5; // No instructions generated for this, as it is unreachable.
Upvotes: 2