0

I have a question related to c++ exceptions. I understand that in many cases throwing exceptions is better than returning error values. However, I do find the following situation where returning error values is more feasible then exceptions:

 bool run_a_function()
 {  

    if (!function_step1())
        return false;
    if (!function_step2())
        return false;
    if (!function_step3())
        return false;
    if (!function_step4())
        return false;

}

As we can see from the above codes, in order to finish a function, several steps are needed. If one step fails, a false value is returned. Then when an operator use the function run_a_function he can make sure that the program will not crash even this function does not run well:

 if (run_a_function())
    do_something();
 else
    do_other_things();

However, if we use exceptions:

void run_a_function()
 {  

    try
   {
      function_step1();
      function_step2();
      function_step3();
      function_step4();
    }
    catch (...)
    {
     }
  }

then I have the risk that the program crash and an exception is threw. My question is: have I justified returning error values in this case? Are there some guild lines for choosing error values and exceptions? Thanks!

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
feelfree
  • 11,175
  • 20
  • 96
  • 167
  • "I understand that in many cases throwing exceptions is better than returning error values." What is your source for this? I totally disagree. – Daniel Daranas Jun 07 '13 at 08:41
  • 1
    @DanielDaranas "To resume I prefer exceptions over error codes in almost all situations." http://stackoverflow.com/questions/253314/exceptions-or-error-codes – feelfree Jun 07 '13 at 08:43
  • If you read the whole answers, though, error codes clearly have their place, in particular: "Exceptions are for anything that stops or inhibits the method or subroutine from doing what you asked it to do... NOT to pass messages back about irregularities or unusual circumstances, or the state of the system, etc. Use return values or ref (or out) parameters for that." (see the answer http://stackoverflow.com/a/254073/96780). I don't agree with a universal approach for exceptions as better than error codes. – Daniel Daranas Jun 07 '13 at 08:46

1 Answers1

1

check out this http://www.parashift.com/c++-faq/exceptions.html In general I only use return values in performance critical sections when exceptions are proved to be the problem. Also you should never throw across your module boundaries.

Slava
  • 1,528
  • 1
  • 15
  • 23