I found this question Return magic value, throw exception or return false on failure?, however it is kind of broad. I would like a more specific answer.
Say I have a method called Connect() which connects to a remote device over an Ethernet socket. If the socket fails it throws SocketException.
So the way I see it I have 2 valid options.
Option 1: Capture exception and return true.
public void CallConnect()
{
while(!Connect())
{
//** Log error
}
//** do what ever
}
public bool Connect()
{
try
{
_socket.Connect()
return true;
}
catch(SocketException)
{
return false;
}
catch(<SomeOtherException1>)
{
return false;
}
catch(<SomeOtherException2>)
{
return false;
}
}
Option 2: Throw Generic Exception
public void Connect()
{
try
{
_socket.Connect()
}
catch(SocketException ex)
{
throw new ConnectionException("Blah blah I failed 1", ex);
}
catch(<SomeOtherException1>)
{
throw new ConnectionException("Blah blah I failed 2", ex);
}
catch(<SomeOtherException2>)
{
throw new ConnectionException("Blah blah I failed 3", ex);
}
}
public void CallConnect()
{
bool connected == false;
while(!connected)
{
try
{
Connect();
connected = true;
}
catch(ConnectionException)
{
//** Log error
}
}
}
My understanding if a failure is a normal or expected behavior, that no exception should be thrown, but if failure should never happen then yes an exception should be thrown.
Failing to connect could be considered expected behavior if for enable someone unplugs the Ethernet cable, or someone turns off the device it needs to communicate with, but it could also be consider exceptional behavior too.
Now if I were to ask how should handle it if send fails after I have successfully connected, I think that answer is obviously throw an exception.