Search code examples
c#exceptionreturn-code

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 ?.


Solution

  • how about:

    for(int i = 0; i < n; i++)
    {
      try
      {
        myCall();
      }
      catch(Exception e)
      {
        Log(String.Format("Problem with {0}", i));
      }
    }