Reputation: 1
I would like to seek for your inputs regarding this problem on what could be the possible approaches.
A simple illustration of what i like to achieve is this.
Behavior
void foo(const std::string value){
//Several lines above
if( value.empty() ){
ERROR_LOG("value is empty");
return ;
}
//Several lines below
}
I would like something similar but approach is like this below:
static inline check(bool pred, std::string message){
if(!pred){
ERROR_LOG("%s", message);
// The problem is the part after this,
// How do I achieve to terminate only the calling function but not the whole program.
std::terminate();
}
}
void foo(const std::string value){
// Several lines above
check( !value.empty(), "Error, Value is empty" );
// Several lines below
}
I would like to create a helper function called check
for a readable code. Please note that the "Several lines" comment may indicate 300+ lines of code. The first method would surely work but I would like to achieve a similar result on a cleaner approach.
I have already tried the following exit(0), std::terminate(), abort() but all these would stop the entire program. Thanks
Upvotes: 0
Views: 621
Reputation: 615
I think you can mange it using Exceptions. Somethng like
static inline check(bool pred, std::string message){
if(!pred){
ERROR_LOG("%s", message);
throw new Exception("message");
}
}
void foo(const std::string value){
// Several lines above
try
{
check( !value.empty(), "Error, Value is empty" );
// Several lines below
}
catch(Exception)
{
// manage your case here
}
}
Of course using this pattern the Exception management could be done at any level of the call stack
Upvotes: 1