Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions vs return codes : do we lose something (while gaining something else)?

My question is pretty vague :o) - But here is an example :

When I was writing C code, I was able to log counter's value when something failed :

   <...>
   for ( int i = 0 ; i < n ; i++ )
      if ( SUCCESS != myCall())
         Log( "Failure, i = %d", i );
   <...>

Now, using exceptions, I get this :

  try
   {
      <...>
      for ( int i = 0 ; i < n ; i++ )
         myCall();
      <...>
   }
   catch ( Exception exception )
   {
      Log( "Failure ! Maybe in myCall() ? Don't know. i's value ? No clue." );
   }

Of course, one may declare "i" outside of the try/catch statement (and this is what I'm doing). But I don't like it - I like declare variable where they are used, not before.

But maybe am I missing something here. Do you have any elegant solution ?

Thank in advance ! Sylvain.

ADDED : myCall() is an obscure API call - I have no clue what it can throw. Also, I can of course add a Try/Catch block around each call, but I would then be better to use return codes ? Would I then add a lot of noise around important lines of code ?.

like image 338
Sylvain Rodrigue Avatar asked Jan 14 '09 21:01

Sylvain Rodrigue


2 Answers

how about:

for(int i = 0; i < n; i++)
{
  try
  {
    myCall();
  }
  catch(Exception e)
  {
    Log(String.Format("Problem with {0}", i));
  }
}
like image 150
scottm Avatar answered Oct 30 '22 20:10

scottm


I think you've got it wrong, and its not surprising as many other people do too.

Exceptions are not to be used for program flow. Read that again, its important.

Exceptions are for the "whoo, that's wasn't supposed to happen" errors that you hope never to see at runtime. Obviously you will see them the moment your first user uses it, which is why you have to consider the cases where they might happen, but you should still not try to put code in to catch, handle and continue as if nothing had happened.

For errors like that, you want error codes. If you use exceptions as if they were 'super error codes' then you end up writing code like you mentioned - wrapping every method call in a try/catch block! You might as well return an enum instead, its a lot faster and significantly easier to read error return code than litter everything with 7 lines of code instead of 1. (its also more likely to be correct code too - see erikkallen's reply)

Now, in the real world, it is often the case that methods throw exceptions where you'd rather they didn't (EndOfFile for example), in which case you have to use the "try/catch wrapper" anti-pattern, but if you get to design your methods, don't use exceptions for day-to-day error handling - use them for exceptional circumstances only. (yes, I know its difficult to get this kind of design right, but so is much of design work)

like image 44
gbjbaanb Avatar answered Oct 30 '22 19:10

gbjbaanb