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)
{
try
{
// 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:
- Return an error code
- 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. - 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?