Exceptions Again

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

What type of exception should I throw when my code detects that a
connection has dropped (i.e. NetworkStream.Read() returns 0)?

Should I just throw a SocketException or should I create my own class
and throw that instead -- what would be the usual practise in a case
like this?
 
Hi,

The best way would be to return the error as a parameter (less overhead).
If you have to throw an exception then you should inherit from
ApplicationException.
 
Miha Markic said:

Hi Miha,
The best way would be to return the error as a parameter (less overhead).
If you have to throw an exception then you should inherit from
ApplicationException.

This is interesting -- in my current code, I'm already doing something
like this: the method returns a success value indicating if the
connection dropped (false if dropped). I was looking at this code
last night and thought that throwing an exception might be a more .NET
way of doing something like this, and was considering changing the
code to throw an exception instead.

Well, I guess this is one of those debatable things...

Cheers
 
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
 
C# Learner said:
This is interesting -- in my current code, I'm already doing something
like this: the method returns a success value indicating if the
connection dropped (false if dropped). I was looking at this code
last night and thought that throwing an exception might be a more .NET
way of doing something like this, and was considering changing the
code to throw an exception instead.

Well, I guess this is one of those debatable things...

It certainly is debatable, but I'd go the exception route - and I'd
throw an IOException of some description, quite possibly a
SocketException. I personally don't think there's any reason to create
a new exception type if there's one which already describes the
situation perfectly well. I only use ApplicationException for
exceptions which are application-specific. (I'm considering creating a
LibraryException which is the equivalent of ApplicationException for
libraries, too.)
 
Respectfully, I do not agree that you should use the framework exception
every time.

If I generate an exception, I usually want to handle that exception
differently than one
generated by the framework. On the other hand, if I simply log an
exception, or propogate it upstream,
then it makes very good sense not to add code by declaring my own exception.

Different purposes lead to different things.

So I'd say, for an exception that you generate in response to an event that
the framework does not detect,
declare your own exception, derived from the most appropriate Exception
class (not all from ApplicationException).

HTH,
--- Nick
 
Andreas Huber said:
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

Hi Andreas,

I agree with your point of view on this post. However, I just wanted to
make this clarification on Microsoft guidance. This is what they say in
their Patterns and Practices section of the MSDN Architecture Center in the
document titled "Exception Management Architecture Guide":

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp

--- Begin Quote ---

Designing Your Application Exception Hierarchy

The .NET Framework provides an extensive hierarchy of exception classes. If
a suitable exception class is already provided by the .NET Framework, use it
instead of creating a new class. You should only create a new application
exception class for an exception type that you need to react to and handle
within your code that is not already available in your application exception
hierarchy or in the Framework. Most application exception hierarchies should
be fairly flat with grouping used for organization purposes or to allow some
set of application exceptions to inherit common properties or functionality.

--- End Quote ---

I think there is more to be said about exception handling and
instrumentation as we gain more experience, but I believe the MSDN
Architecture Center is a real good start. Like I said, I agree with your
views on this and thought that it would be useful to mention this
information.

Joe
 
I use the following strategy:

I only use exceptions for "exceptional situations", never to indicate a
"special result" that the caller is supposed to handle and treat in a
specific way (If I need a special result then I design my API so that it
returns a boolean or a special object and I don't use exception handling).

With this strategy, I never have to "discriminate" among exceptions because
they all mean the same thing: "something has failed". So, I always catch
"all exceptions", either to wrap them into a higher level exception and
repropagate them, or to log them, inform the user and continue (usually,
this happens in an event loop or event dispatcher).

Also, with this strategy, I don't care whether the exception is an
XxxException or a YyyException and I always use one exception class (some
kind of MyApplicationException) for all the exceptions that I throw.

I know that this approach is a bit unusual but it has some advantages:

* All the "application logic" is expressed with "normal" flow of control
(if/then/else, while loops, returns, etc), not with try/catch.

* The "application logic" is efficient because it never relies on try/catch.

* All exceptions follow the same path, so you can analyze the exception
handling logic separately from the normal application logic, and verify that
all exceptions (all abnormal events) will be properly logged and reported
and that the application will be robust. You can do this analysis without
any knowledge about what the application logic is supposed to do.

* You don't waste time on issues like this one: should I define my own
exception class or use the framework class? A single exception class is all
you need.

* The EH code is very regular and very easy to analyze. Basically, there are
only three patterns: a) throw, b) catch all, wrap, rethrow, c) catch all,
log, report and continue. And developpers write a lot less try/catch than if
they use exceptions as "special returns". So you don't need to analyze long
lists of specific catch clauses to verify that exceptions are properly
handled.

Bruno.
 
Joe said:
Hi Andreas,

I agree with your point of view on this post. However, I just wanted
to
make this clarification on Microsoft guidance. This is what they say
in
their Patterns and Practices section of the MSDN Architecture Center
in the
document titled "Exception Management Architecture Guide":

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asp
[snip quote]

Interesting, I only knew the guidelines here:

http://msdn.microsoft.com/library/d...n-us/cpguide/html/cpconthrowingexceptions.asp
<partialquote>
- In most cases, use the predefined exceptions types. Define new exception
types only for programmatic scenarios. Introduce a new exception class to
enable a programmer to take a different action in code based on the
exception class.
- Do not derive user-defined exceptions from the Exception base class. For
most applications, derive custom exceptions from the ApplicationException
class.
I think there is more to be said about exception handling and
instrumentation as we gain more experience, but I believe the MSDN
Architecture Center is a real good start. Like I said, I agree with
your
views on this and thought that it would be useful to mention this
information.

Thanks, that's good to know. I frequently had a bit of a hard time defending
my views about exception handling because Microsoft sais something different
in the quoted guidelines.

Regards,

Andreas
 
Nick said:
Respectfully, I do not agree that you should use the framework
exception every time.

I guess I was not clear enough. I think you should only use framework
exceptions if they can convey the information you need to communicate to
your direct and/or indirect callers. If there is no such exception in the
framework you definitely should throw your own exceptions. Such exceptions
should typically derive from the most appropriate framework exception.
If I generate an exception, I usually want to handle that exception
differently than one
generated by the framework.

Exactly.

Regards,

Andreas
 
It certainly is debatable, but I'd go the exception route - and I'd
throw an IOException of some description, quite possibly a
SocketException.

<snip>

Okay, I've rewrote the code to use exceptions instead. As expected,
the "readability" of the code in the three methods involved is greatly
improved.

Thanks all.
 
Back
Top