I was doing some .NET coding today and I ran into something I hadn't thought about before -- many of Microsoft's built-in methods for testing network connectivity (ping, TCP sockets, etc.) are very liberal about throwing exceptions if the connection fails.
Of course, in general cases it's not good to use exceptions in your program's control flow. I'm curious though -- if the .NET libraries so readily throw them, how can I avoid something like this (excuse possibly messy code, just throwing together an example):
bool TestConnection(string host)
{
bool connected;
Ping ping = new Ping();
PingReply reply = ping.Send(host);
connected = (reply.Status == IPStatus.Success);
return connected; // possibly won't return false because of exceptions
}
I could use a try-catch
block to handle the exception, but all I'd be doing is setting connected
to false. Isn't that basically swallowing the exception altogether since I'm discarding all the information from the exception? What's the best practice here?