Miha said:
Hi,
The best way would be to return the error as a parameter (less
overhead).
Given the problem of the OP (connection dropped) I would say the overhead is
irrelevant. Presumably the error happens very infrequently. In such a
scenario the exception approach tends to be faster than the equivalent error
return-code because try-blocks are faster than ifs as long as no exception
is thrown. This is especially true when the error/success information must
be propagated over many call-stack levels.
Even if connections are dropped frequently, the overhead of exceptions is
typically small compared to the time spent communicating over the network.
Therefore, I believe using return values to signal an error is not a good
idea in OP's situation. Generally one should refrain from optimizing (and
often also obfuscating) code that has never been profiled. Programmers are
usually very bad at guessing what will and will not be a performance
bottleneck.
If you have to throw an exception then you should inherit
from ApplicationException.
This is more or less what Microsoft recommends in MSDN. However, when
examined closely, this rule does not make a whole lot of sense. For
starters, even Microsoft does not follow this guideline. Otherwise e.g.
TargetInvocationException would not be a subclass of ApplicationException
and all most-derived exception types that are subclasses of SystemException
would be sealed.
Moreover, there are quite a few framework exceptions where implementing your
own ApplicationException-derived counterpart adds nothing but more code
(e.g. ArgumentException, ArgumentNullException,
ArgumentOutOfRangeException). Whenever such an exception is thrown the whole
process must presumably be teared down anyway (or at least enter a fault
mode where a technician can diagnose the problem), so why is it better to
signal an equivalent problem in user-code with a different
(ApplicationException-derived) exception? The resulting remedy is exactly
the same and the ultimate cause can always be determined by examining the
stack-trace.
Only when the framework does not yet offer an exception that could convey
the information you want to put into it should you implement your own
exceptions. Even then it is a good idea to see whether the framework offers
a suitable baseclass so that your users can react to similar problems with a
catch on the base.
Regards,
Andreas