473,385 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Exceptions Again

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?
Nov 15 '05 #1
11 1435
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 - RightHand .NET consulting & development
miha at rthand com
www.rthand.com

"C# Learner" <cs****@learner.here> wrote in message
news:eg********************************@4ax.com...
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?

Nov 15 '05 #2
"Miha Markic" <miha at rthand com> wrote:
Hi,
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
Nov 15 '05 #3
Miha Markic wrote:
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

Nov 15 '05 #4
C# Learner <cs****@learner.here> wrote:
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...


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.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
Yes, probably better :)

--
Miha Markic - RightHand .NET consulting & development
miha at rthand com
www.rthand.com

"Andreas Huber" <ah****@gmx.net> wrote in message
news:40**********@news.bluewin.ch...
Miha Markic wrote:
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

Nov 15 '05 #6
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" <ah****@gmx.net> wrote in message
news:40**********@news.bluewin.ch...
Miha Markic wrote:
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

Nov 15 '05 #7
"Andreas Huber" <ah****@gmx.net> wrote in message
news:40**********@news.bluewin.ch...
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


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/de...ceptdotnet.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
--
http://www.csharp-station.com
Nov 15 '05 #8
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.

"C# Learner" <cs****@learner.here> a écrit dans le message de
news:eg********************************@4ax.com...
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?

Nov 15 '05 #9
Joe Mayo wrote:
"Andreas Huber" <ah****@gmx.net> wrote in message
news:40**********@news.bluewin.ch...
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


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/de...ceptdotnet.asp [snip quote]

Interesting, I only knew the guidelines here:

http://msdn.microsoft.com/library/de...exceptions.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.
</partialquote>
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

Nov 15 '05 #10
Nick Malik wrote:
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

Nov 15 '05 #11
Jon Skeet [C# MVP] <sk***@pobox.com> wrote:

<snip>
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.
Nov 15 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Zunbeltz Izaola | last post by:
Hi, I've the following problem with try/exception. I've a try block that will raise some exceptions. I want the program to ignore this exceptions completely. Is it possible? Thanks in...
33
by: Steven Bethard | last post by:
I feel like this has probably been answered before, but I couldn't find something quite like it in the archives. Feel free to point me somewhere if you know where this has already been answered. ...
26
by: OvErboRed | last post by:
I just read a whole bunch of threads on microsoft.public.dotnet.* regarding checked exceptions (the longest-running of which seems to be <cJQQ9.4419 $j94.834878@news02.tsnz.net>. My personal...
24
by: mag31 | last post by:
Is there any way to find out if a particular .net function will throw an exception without first generating the exception? I am using structured exception handling i.e. try catch finally blocks...
15
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions...
16
by: Einar Høst | last post by:
Hi, I'm getting into the Trace-functionality in .NET, using it to provide some much-needed logging across dlls in the project we're working on. However, being a newbie, I'm wondering if some...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
29
by: mailforpr | last post by:
Sometimes, I can't think of any good reason why I should have the program's logic thrown an exception. Except for catching the exception and printing "Uh, oh" to the screen. I also think that in...
6
by: Liming | last post by:
Hi, In a typical 3 tier model (view layer, busines layer and data access layer) where do you handle your exceptions? do you let it buble up all the way to the .aspx pages or do you handle it in...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.