A question regarding try/catch
Here is the code(psedo code),
Code:
bool foo()
{
try{
if thing one is not done
return false;
if thing two is not done
return false;
}
catch(...)
{
do something...
}
return true;
}
My question is that within catch clause, should I call return false at the end? Thanks.
Re: A question regarding try/catch
It only depends on what the return value of this function means.
If the case of exception means false then return false, it it means true then return true.
If it depends upon the exception code/error number/or something similar - then it is up to you to choose what to return: true or false...
Re: A question regarding try/catch
Quote:
Originally Posted by
VictorN
It only depends on what the return value of this function means.
If the case of exception means false then return false, it it means true then return true.
If it depends upon the exception code/error number/or something similar - then it is up to you to choose what to return: true or false...
The problem is there is no way to decide whether it should return true or false when an exception is thrown. For example, when we call the statement "if thing one is not done" , it may throw an exception. So in this case, should I return true or false in the catch clause? This is really confusing...
Re: A question regarding try/catch
More typically you'd throw in the function and put the try/catch in the function that calls it. That way you'd know if it returned legitimately or threw the exception.
Code:
void bar()
{
try
{
if(foo())
...
}
catch(...)
{
...
}
}
If you need the catch in foo, typically returning true would indicate foo succeeded, and false would indicated it didn't.
Re: A question regarding try/catch
Quote:
Originally Posted by
LarryChen
Here is the code(psedo code),
Code:
bool foo()
{
try{
if thing one is not done
return false;
if thing two is not done
return false;
}
catch(...)
{
do something...
}
return true;
}
My question is that within catch clause, should I call return false at the end? Thanks.
You could try the "update the return value as you go" scheme:
Code:
ReturnType foo()
{
ReturnType return_val = a;
try{
return_val = b;
if (thing_one_is_not_done)
{
return_val = c;
return return_val;
}
return_val = d
if (thing_two_is_not_done)
{
return_val = e;
return return_val;
}
return_val = f
}
catch(...)
{}
return return_val;
}
You can update this scheme: instead of doing "if-return; if-return", you can go for the "if{if{if{ifi{}}}}" scheme. You can replace the intermediate "return return_val" with "goto end;".
Regardless of what you are doing, the scheme of "update your return value as you go" is pretty to use. Its not the most efficient, but more often than not, it makes coding really easy.