I looking at the best way to handle exceptions, the answer to this question may be to handle the exception in a different place or to not handle to exception at all but to control the flow of the code. Please let me know if this is the case.

Lets say we have a class NetworkConnection. This class has a Connect method that looks like:

bool Connect(string ipAddress, int port)
       // do connection, when successful
       return true;
   catch (HostNotFoundException ex)
       return false;
   catch (...)

If another object using this method wants to know what exception occurred it cannot find out. There are three ways of dealing with this that I can think of:

  1. Return an error code
  2. Store a variable on the NetworkConnection object that contains some error info, perhaps a string saying 'Host not found', this can then be queried by another object later on.
  3. Catch the exception higher up in the code base.

I want to choose the second method but I sense that this would be a bad idea. What is the best decision here, why (potentially) is my chosen bad?


Its a reasonably common practice - C programs (and other systems, eg errno) often to store the last error in a location so you can pick the details out if a function returned an error code. There's no reason why you can't do the same.

However, if you do this you have to take a few things into consideration. Threads are very important, each error info must be stored per thread and you cannot get anything but the very-last-error, which could be tricky if you are expecting a different area of code to read it - a different call may change it between the time you write it and you want to read it. As a result, its not recommended in general.

What you might want to do is log all errors and let the other routine read off the list, this may work for auditing or errors that are specifically designed for the user to view.

IMHO exceptions are for exceptional circumstances. For expected errors, a return code is superior. Using exceptions for code-flow is bad practice. Return an error code and let the caller decide what to do with that. IF you must use exceptions, handle it further up the call stack.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.