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?