hi and thanks for reading. im a newbie in programming and C# and sockets programming. in my code i try and catch problems to provide fault tolarence in my app. the following:
As a general guideline, don't catch System.Exception
. It's a bad idea and a bad code smell indicative of a failure to grasp the purpose of exceptions. I believe it's the result of a dev's belief that exceptions are the error instead of the code that triggered the exception.
I see this failure in production code all the time, and it invariably masks real errors as valid and useful exceptions are caught and swallowed, leaving the application in a bad state. This makes it much trickier to track down the root cause of a failure.
Catching exceptions using the method you've used here is more-or-less the right way to do it. There are a few things you might want to consider improving on, though:
Don't generally treat an ArgumentNullException
or ArgumentOutOfRangeException
as a runtime network failure (unless it really is). Rather, it should be considered a logic error that causes your program to fail as quickly as possible (so that you can check it out with a debugger as close as possible to the point of failure). This frequently means not catching any ArgumentException
at all.
Consider examining the exception hierarchy to find an appropriate base exception that covers the exceptions you're trying to report. E.g., (I haven't looked it up), suppose that three of your exceptions all derived from SocketException
. You might save some typing by catching a SocketException
instead of the three separate exception. Only do this if you're reporting all socket exceptions, however. (This is basically a more disciplined version of your original attempt to just catch Exception
)
Because both lines in every exception handler are identical, you may create a function to do those two lines of work in a single line in the handler. Typical don't-repeat-yourself refactoring. If you want to change the way you report your exception, think about how much easier it would be to change a single function than all those individual handlers.
Just about any significant I/O (network and file come to mind) is going to entail a pretty significant chain of exception handlers just because there's so much that can go wrong. Seeing a lot of error reporting around I/O that may fail isn't an anti-pattern, but it may be a good code smell. Like pine-fresh scent or freshly baked bread. :)