By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,507 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,507 IT Pros & Developers. It's quick & easy.

Try-Catch Implementation Guidelines?

P: n/a
Has somebody written any guidelines regarding how to determine when
try-catch blocks should be used and where their use would or could be
considered superfluous?

<%= Clinton Gallagher
METROmilwaukee (sm) "A Regional Information Service"
NET csgallagher AT metromilwaukee.com
URL http://metromilwaukee.com/
URL http://clintongallagher.metromilwaukee.com/
Nov 17 '05 #1
Share this Question
Share on Google+
37 Replies


P: n/a
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.

Some ways that try/catch can be used would be considered poor coding
practice, such as for flow-control.

Nov 17 '05 #2

P: n/a
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.

Some ways that try/catch can be used would be considered poor coding
practice, such as for flow-control.

Nov 17 '05 #3

P: n/a


gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.
I cannot find that in the guidelines linked.

My personal guide-lines are to never catch (and thus *only*
try...finally) except when:

- You can retry, doing something to fix the error
- You are at the top of the stack, where you need to decide whether
the app should terminate or try some form of recovery.
- You are gathering results from a collection of operations. In this
case I often use callbacks to the caller so the caller can decide if
operations should halt here or proceed.
- You wish (for some reason) to log the exception on it's way to your
caller. In this case the pattern:

try {
...;
} catch ( Exception e ) {
Log(e);
throw;
}

is very helpfull.
Some ways that try/catch can be used would be considered poor coding
practice, such as for flow-control.


Such as flow-control ;)

As a rule of thumb, don't catch exceptions unless you *need* to do it or
can apply some remedy. Remember that you can also try...finally and "using".

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #4

P: n/a


gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.
I cannot find that in the guidelines linked.

My personal guide-lines are to never catch (and thus *only*
try...finally) except when:

- You can retry, doing something to fix the error
- You are at the top of the stack, where you need to decide whether
the app should terminate or try some form of recovery.
- You are gathering results from a collection of operations. In this
case I often use callbacks to the caller so the caller can decide if
operations should halt here or proceed.
- You wish (for some reason) to log the exception on it's way to your
caller. In this case the pattern:

try {
...;
} catch ( Exception e ) {
Log(e);
throw;
}

is very helpfull.
Some ways that try/catch can be used would be considered poor coding
practice, such as for flow-control.


Such as flow-control ;)

As a rule of thumb, don't catch exceptions unless you *need* to do it or
can apply some remedy. Remember that you can also try...finally and "using".

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #5

P: n/a
gmiley <gm****@gmail.com> wrote:
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


Heck no - only catch an exception if either you're going to rethrow it
(eg wrapped in another exception), or if you can recover from the
exception and continue anyway, or if you're a relatively top-level
piece of code which should abort the current bit of work and move onto
the next one.

Catching exceptions you can't recover from and leaving them caught
makes exceptions almost completely useless.

Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.

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

P: n/a
gmiley <gm****@gmail.com> wrote:
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


Heck no - only catch an exception if either you're going to rethrow it
(eg wrapped in another exception), or if you can recover from the
exception and continue anyway, or if you're a relatively top-level
piece of code which should abort the current bit of work and move onto
the next one.

Catching exceptions you can't recover from and leaving them caught
makes exceptions almost completely useless.

Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.

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

P: n/a
On Wed, 31 Aug 2005 21:51:42 +0200, Helge Jensen wrote:
gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure.. it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?

Thanks :)

--
Andrew
Nov 17 '05 #8

P: n/a
On Wed, 31 Aug 2005 21:51:42 +0200, Helge Jensen wrote:
gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure.. it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?

Thanks :)

--
Andrew
Nov 17 '05 #9

P: n/a
Andrew <no******************@earth.universe> wrote:
I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure.. it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?


Exceptions are only "expensive" when they're thrown - entering a try
block isn't expensive at all (there are a few JIT restrictions, but
it's almost free). When an exception is thrown, the more layers of
stack it has to unwind, the more expensive it is - but the less likely
you are to be calling the same code again immediately.

The idea that exceptions are truly expensive is a myth, however - if
you use exceptions reasonably, you're very, very unlikely to ever see
them become a performance problem.

See http://www.pobox.com/~skeet/csharp/exceptions.html

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

P: n/a
Andrew <no******************@earth.universe> wrote:
I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure.. it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?


Exceptions are only "expensive" when they're thrown - entering a try
block isn't expensive at all (there are a few JIT restrictions, but
it's almost free). When an exception is thrown, the more layers of
stack it has to unwind, the more expensive it is - but the less likely
you are to be calling the same code again immediately.

The idea that exceptions are truly expensive is a myth, however - if
you use exceptions reasonably, you're very, very unlikely to ever see
them become a performance problem.

See http://www.pobox.com/~skeet/csharp/exceptions.html

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

P: n/a
Yes, taking a performance hit is one concern but there are so many
circumstances one must wonder what a best practice should/could/would be. I
appreciate the responses and looks like a good fight is brewing ;-)

<%= Clinton Gallagher

"Andrew" <no******************@earth.universe> wrote in message
news:9g*****************************@40tude.net...
On Wed, 31 Aug 2005 21:51:42 +0200, Helge Jensen wrote:
gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure..
it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just
what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?

Thanks :)

--
Andrew

Nov 17 '05 #12

P: n/a
Yes, taking a performance hit is one concern but there are so many
circumstances one must wonder what a best practice should/could/would be. I
appreciate the responses and looks like a good fight is brewing ;-)

<%= Clinton Gallagher

"Andrew" <no******************@earth.universe> wrote in message
news:9g*****************************@40tude.net...
On Wed, 31 Aug 2005 21:51:42 +0200, Helge Jensen wrote:
gmiley wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure..
it's
probably better to use them than to have your program just die on your
users.

Not that I'm particularly experienced at C# or anything.. this is just
what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?

Thanks :)

--
Andrew

Nov 17 '05 #13

P: n/a
> Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.
I emphatically agree with this philosophy. I can't begin to count the number
uncontrolled program terminations I've seen which stem from the fact that
the developer *assumed* that a particular statement or group of statements
were 'safe'.

I'm speaking from a VB6 perspective, so the mechanics of what I've done in
the past don't directly relate to C#, but the philosophy does. We have
(almost*) every low level method implemting a standard low-level error
handler, and every top level method (UI event handlers) implementing a
standard top-level error handler. We're not perfect, we do sometimes
encounter runtime errors, but the system does not crash. (If it does, it's
because someone forgot to implement a top-level error handler.)

(* almost - We're not fanatical. A property let or set which simply marshals
a value through a class interface is not likely to implement an error
handler. Yeah, we could run out of memory and even such a simple statement
could fail. But then the game's pretty much over anyway. Without memory, how
would an error be processed?)

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... gmiley <gm****@gmail.com> wrote:
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


Heck no - only catch an exception if either you're going to rethrow it
(eg wrapped in another exception), or if you can recover from the
exception and continue anyway, or if you're a relatively top-level
piece of code which should abort the current bit of work and move onto
the next one.

Catching exceptions you can't recover from and leaving them caught
makes exceptions almost completely useless.

Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #14

P: n/a
> Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.
I emphatically agree with this philosophy. I can't begin to count the number
uncontrolled program terminations I've seen which stem from the fact that
the developer *assumed* that a particular statement or group of statements
were 'safe'.

I'm speaking from a VB6 perspective, so the mechanics of what I've done in
the past don't directly relate to C#, but the philosophy does. We have
(almost*) every low level method implemting a standard low-level error
handler, and every top level method (UI event handlers) implementing a
standard top-level error handler. We're not perfect, we do sometimes
encounter runtime errors, but the system does not crash. (If it does, it's
because someone forgot to implement a top-level error handler.)

(* almost - We're not fanatical. A property let or set which simply marshals
a value through a class interface is not likely to implement an error
handler. Yeah, we could run out of memory and even such a simple statement
could fail. But then the game's pretty much over anyway. Without memory, how
would an error be processed?)

- Joe Geretz -

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... gmiley <gm****@gmail.com> wrote:
MSDN has some good information on this subject.

http://msdn.microsoft.com/library/en...exceptions.asp

Basically, if you know oyu can prevent an exception by checking states
or some other method/property return value, then use that route.
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.


Heck no - only catch an exception if either you're going to rethrow it
(eg wrapped in another exception), or if you can recover from the
exception and continue anyway, or if you're a relatively top-level
piece of code which should abort the current bit of work and move onto
the next one.

Catching exceptions you can't recover from and leaving them caught
makes exceptions almost completely useless.

Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #15

P: n/a
Joseph Geretz <jg*****@nospam.com> wrote:
Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.


I emphatically agree with this philosophy. I can't begin to count the number
uncontrolled program terminations I've seen which stem from the fact that
the developer *assumed* that a particular statement or group of statements
were 'safe'.

I'm speaking from a VB6 perspective, so the mechanics of what I've done in
the past don't directly relate to C#, but the philosophy does. We have
(almost*) every low level method implemting a standard low-level error
handler, and every top level method (UI event handlers) implementing a
standard top-level error handler. We're not perfect, we do sometimes
encounter runtime errors, but the system does not crash. (If it does, it's
because someone forgot to implement a top-level error handler.)


What's the point in having a handler in almost every method though?
Does it actually add any value? Why not just let the exception bubble
up from the low level method to the high level method?

I very rarely write a catch block - most errors are unrecoverable for
that unit of work, which usually goes right up to the top level.

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

P: n/a
Joseph Geretz <jg*****@nospam.com> wrote:
Also bear in mind that an exception can pretty much *always* be thrown
- the thread could be aborted, or you could run out of memory.


I emphatically agree with this philosophy. I can't begin to count the number
uncontrolled program terminations I've seen which stem from the fact that
the developer *assumed* that a particular statement or group of statements
were 'safe'.

I'm speaking from a VB6 perspective, so the mechanics of what I've done in
the past don't directly relate to C#, but the philosophy does. We have
(almost*) every low level method implemting a standard low-level error
handler, and every top level method (UI event handlers) implementing a
standard top-level error handler. We're not perfect, we do sometimes
encounter runtime errors, but the system does not crash. (If it does, it's
because someone forgot to implement a top-level error handler.)


What's the point in having a handler in almost every method though?
Does it actually add any value? Why not just let the exception bubble
up from the low level method to the high level method?

I very rarely write a catch block - most errors are unrecoverable for
that unit of work, which usually goes right up to the top level.

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

P: n/a


Andrew wrote:
Otherwise, if you are unsure about a block of code and believe that
there could be an exception thrown, use try/catch blocks.
I cannot find that in the guidelines linked.


Please correct me if I'm wrong.. but.. I believe he is referring to the
fact that exceptions are very expensive, and thus one should generally not
use them if there's another way to handle things. If you aren't sure.. it's
probably better to use them than to have your program just die on your
users.


OP states (rephrased) "if you are in doubt, catch". I say "never catch
unless[list of criteria]", and I point out that I cannot find the OP
statement substantiated in the linked guidelines.

I can't really see how performance comes into this.
Not that I'm particularly experienced at C# or anything.. this is just what
I've heard.. However.. Are they significantly less costly if you do not
catch and simply use finally?


I cannot change whether an exception is thrown by selecting to "catch"
or "finally", the expensive bit already happened, besides performance is
a concern second to correct programs.

Catch has nothing to do with cleanup, but with recovery from an error
(see previous post). Thus, I use finally, not for "performance", but for
correctness. Cleanup-code that *must* run after some other code must go
into either one of:

- An object which someone is responsible for Dispose()ing
- A finally clause

I, as a rule of thumb, only consider performance when:

- Designing the data-structures to hold large amounts of data
- The profiler can pin-point some part of the program where a lot of
cpu-time is spent.

And, generally, I try to do "streaming" processing of large data-sets,
so I don't need all of it randomly-accessible at any time -- where possible.

Good performance is rarely possible through the selection of syntax, but
rather through selection of data-structures and algorithms. Correctness,
on the other hand, often depends on proper selection of syntax.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #18

P: n/a
Hi Jon,
What's the point in having a handler in almost every method though?
Does it actually add any value?
Yes. I'm not going to spec out the whole error handling subsystem but in a
nutshell we accumulate an XML string inside Err.Helpfile (which we're not
using otherwise) which details the entire stack plus local variables
(optional) as the stack unwinds. The XML Stack Trace is the payload, and the
Err object is the transport mechanism we use to bubble this information up
to the UI in the event of an error. No extra parameters are necessary and
the Err object is a great mechanism which even mashals nicely across
hardware boundaries.

The top level error handler presents this nicely formatted in our standard
runtime error dialog box. We've found that having the entire stack trace is
essential to quick diagnosis of runtime errors since there are many ways to
get from point A to point B. In many cases point B is essentially coded
properly, however certain state which is the result of a particular exeution
path causes a problem in esoteric conditions. The Stack Trace enlightens us
as to what precisely those conditions are. Very helpful during development
as well.

- Joe Geretz -
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Joseph Geretz <jg*****@nospam.com> wrote:
> Also bear in mind that an exception can pretty much *always* be thrown
> - the thread could be aborted, or you could run out of memory.


I emphatically agree with this philosophy. I can't begin to count the
number
uncontrolled program terminations I've seen which stem from the fact that
the developer *assumed* that a particular statement or group of
statements
were 'safe'.

I'm speaking from a VB6 perspective, so the mechanics of what I've done
in
the past don't directly relate to C#, but the philosophy does. We have
(almost*) every low level method implemting a standard low-level error
handler, and every top level method (UI event handlers) implementing a
standard top-level error handler. We're not perfect, we do sometimes
encounter runtime errors, but the system does not crash. (If it does,
it's
because someone forgot to implement a top-level error handler.)


What's the point in having a handler in almost every method though?
Does it actually add any value? Why not just let the exception bubble
up from the low level method to the high level method?

I very rarely write a catch block - most errors are unrecoverable for
that unit of work, which usually goes right up to the top level.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #19

P: n/a
There are several reasons for Catching exceptions. For instance, in my
work environment we write in-house applications for our entire
organization. We deal with very sensitive data. We cannot afford to
have an exception not dealt with.

We do have a top-level error handler object, but at lower portions of
code we cannot simply try a block, let an exception occurr, and issue a
finally cleanup.

We have to take into account which exception actually occurred, we have
to then decide what to do with that particular exception - is this an
exception that is considered 'acceptable' or should this terminate
process and throw up to the calling process (so on and so forth).

Catch is there for a reason folks. It's not flow control, its properly
handling exceptions based on what exactly went wrong.

---

As far as not being able to find one of my statements in the referenced
link in my first post, it is not there directly, but it is most
definately implied by the very first bullet on the page:

"Know when to set up a try/catch block. For example, you can
programmatically check for a condition that is likely to occur without
using exception handling. In other situations, using exception handling
to catch an error condition is appropriate."

.... but if you feel like ignoring potentially problematic code, by all
means, go for it - I just hope I never have to use that software.

My original point was that if at all you can prevent having to use
Try/Catch, then wonderful, but don't be afraid to use it if you think
that either user input, possible programmer error, or some other
potential problem COULD exist.

A programmer should be able to guarentee their own code, but you should
never just assume that someone elses code will work.

Try/Catch/Finally is there for a reason, it's just a matter how you use
it and if you really have no other means around it (for instance,
checking an objects state property).

Nov 17 '05 #20

P: n/a
Joseph Geretz <jg*****@nospam.com> wrote:
What's the point in having a handler in almost every method though?
Does it actually add any value?


Yes. I'm not going to spec out the whole error handling subsystem but in a
nutshell we accumulate an XML string inside Err.Helpfile (which we're not
using otherwise) which details the entire stack plus local variables
(optional) as the stack unwinds. The XML Stack Trace is the payload, and the
Err object is the transport mechanism we use to bubble this information up
to the UI in the event of an error. No extra parameters are necessary and
the Err object is a great mechanism which even mashals nicely across
hardware boundaries.

The top level error handler presents this nicely formatted in our standard
runtime error dialog box. We've found that having the entire stack trace is
essential to quick diagnosis of runtime errors since there are many ways to
get from point A to point B. In many cases point B is essentially coded
properly, however certain state which is the result of a particular exeution
path causes a problem in esoteric conditions. The Stack Trace enlightens us
as to what precisely those conditions are. Very helpful during development
as well.


I agree that it's worthwhile to have the stack trace, but that doesn't
mean you need to catch the exception in each method. It'll still be
available if you just let it bubble up to the top level.

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

P: n/a
gmiley <gm****@gmail.com> wrote:
There are several reasons for Catching exceptions. For instance, in my
work environment we write in-house applications for our entire
organization. We deal with very sensitive data. We cannot afford to
have an exception not dealt with.

We do have a top-level error handler object, but at lower portions of
code we cannot simply try a block, let an exception occurr, and issue a
finally cleanup.

We have to take into account which exception actually occurred, we have
to then decide what to do with that particular exception - is this an
exception that is considered 'acceptable' or should this terminate
process and throw up to the calling process (so on and so forth).

Catch is there for a reason folks. It's not flow control, its properly
handling exceptions based on what exactly went wrong.
Yes - but this is very different from having a catch block in every
method. Where you *can* recover and continue with a particular job of
work, of course it makes sense to catch exceptions - but I suspect
there aren't many applications where that translates to having an
exception handler in pretty much every method, as Joseph was talking
about.
... but if you feel like ignoring potentially problematic code, by all
means, go for it - I just hope I never have to use that software.
I think you're misrepresenting my position hugely here. There's a big
difference between letting an exception bubble up and aborting a large-
scale unit of work (and then letting the user know that it's failed,
logging it etc) and just assuming that exceptions won't happen.
My original point was that if at all you can prevent having to use
Try/Catch, then wonderful, but don't be afraid to use it if you think
that either user input, possible programmer error, or some other
potential problem COULD exist.


There's a difference between potential problems and *recoverable*
problems. If a method can't recover from an exception and still satisfy
its main success contract, there's rarely much point in catching the
exception.

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

P: n/a
> Catch is there for a reason folks. It's not flow control, its properly
handling exceptions based on what exactly went wrong.
So in the .NET environment what do we do for 'unanticipated' errors? It's
impossible ahead of time to predict the entire set of errors which might
possibly occur. (Or even if it were possible, you'd find your application
implementing 99% error handling code and 1% functional processing. I'd say
that's a conservative estimate. There's finite number of ways in which
events can execute properly, and virtually an unlimited number of ways in
which they might go wrong...) Dramatics aside, I always want a generalized
and comprehensive error handling methodology for the purpose of handling
unanticipated errors, without having to go out of my way to anticipate them
specifically.

Basically, in our VB shop our policy is to always anticipate the possibility
of an unanticipated error. We're not going to impose any sort of flow
control in this case. Since the condition is fundamentally unanticipated
there's no way we can continue processing meaningfully. All we want to do is
get out of Dodge and return to the UI while collecting as much stack
information as we can along the way.

Does .NET exception mechanism do this natively for us? The information I'm
interested in having after the stack completely unwinds is:

A. Stack Trace (i.e. App.cmdSave_Click -> App.SaveUser ->
DataBroker.ExecSQL -> OLEDB.Whatever...)
B. Local variable values at various points in this stack trace (Simple
example, the variable UserID = 32768 might point me immediately to an
improperly sized column in the database, or an improperly defined variable
in code.)

Is this natively supported with .NET's exception mechanism, or will I need
to roll my own, just as I've done for the VB6 environment?

Thanks,

- Joe Geretz -

"gmiley" <gm****@gmail.com> wrote in message
news:11********************@g43g2000cwa.googlegrou ps.com... There are several reasons for Catching exceptions. For instance, in my
work environment we write in-house applications for our entire
organization. We deal with very sensitive data. We cannot afford to
have an exception not dealt with.

We do have a top-level error handler object, but at lower portions of
code we cannot simply try a block, let an exception occurr, and issue a
finally cleanup.

We have to take into account which exception actually occurred, we have
to then decide what to do with that particular exception - is this an
exception that is considered 'acceptable' or should this terminate
process and throw up to the calling process (so on and so forth).

Catch is there for a reason folks. It's not flow control, its properly
handling exceptions based on what exactly went wrong.

---

As far as not being able to find one of my statements in the referenced
link in my first post, it is not there directly, but it is most
definately implied by the very first bullet on the page:

"Know when to set up a try/catch block. For example, you can
programmatically check for a condition that is likely to occur without
using exception handling. In other situations, using exception handling
to catch an error condition is appropriate."

... but if you feel like ignoring potentially problematic code, by all
means, go for it - I just hope I never have to use that software.

My original point was that if at all you can prevent having to use
Try/Catch, then wonderful, but don't be afraid to use it if you think
that either user input, possible programmer error, or some other
potential problem COULD exist.

A programmer should be able to guarentee their own code, but you should
never just assume that someone elses code will work.

Try/Catch/Finally is there for a reason, it's just a matter how you use
it and if you really have no other means around it (for instance,
checking an objects state property).

Nov 17 '05 #23

P: n/a
Hi Jon,
I agree that it's worthwhile to have the stack trace, but that doesn't
mean you need to catch the exception in each method. It'll still be
available if you just let it bubble up to the top level.
Will this include local variable values for each method on the stack, or
just the names of the methods themselves? If the trace will include local
variable then I'm certinaly looking forward to this new convenience!

If not though, then I guess its an improvement to capture the stack trace
natively, but I'd still like to have the local variable values for debugging
purposes. If this is not natively provided, then I'll need a covering catch
block in every method in order to capture local variable values at the time
of the exception.

Thanks,

Joe Geretz

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Joseph Geretz <jg*****@nospam.com> wrote:
> What's the point in having a handler in almost every method though?
> Does it actually add any value?


Yes. I'm not going to spec out the whole error handling subsystem but in
a
nutshell we accumulate an XML string inside Err.Helpfile (which we're not
using otherwise) which details the entire stack plus local variables
(optional) as the stack unwinds. The XML Stack Trace is the payload, and
the
Err object is the transport mechanism we use to bubble this information
up
to the UI in the event of an error. No extra parameters are necessary and
the Err object is a great mechanism which even mashals nicely across
hardware boundaries.

The top level error handler presents this nicely formatted in our
standard
runtime error dialog box. We've found that having the entire stack trace
is
essential to quick diagnosis of runtime errors since there are many ways
to
get from point A to point B. In many cases point B is essentially coded
properly, however certain state which is the result of a particular
exeution
path causes a problem in esoteric conditions. The Stack Trace enlightens
us
as to what precisely those conditions are. Very helpful during
development
as well.


I agree that it's worthwhile to have the stack trace, but that doesn't
mean you need to catch the exception in each method. It'll still be
available if you just let it bubble up to the top level.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #24

P: n/a
Ah, but he said local variable values, too. To get those, you have to
catch the exception, add that information (or log it), and (possibly)
rethrow.

gmiley wrote: "We deal with very sensitive data. We cannot afford to
have an exception not dealt with."

That's the rub, isn't it? How do you "deal with" the exception? This is
exactly what Jon is saying.

If you know how to "deal with" the exception and keep going, then catch
it. Unfortunately, it's not common that a piece of code can suffer an
exception and, as you say, "deal with it." Most times, an exception in
a piece of code is fatal: the application cannot recover.

If there is no way to "deal with" the exception: if there is nothing
you can do, then why catch it? What are you going to do with it?
Perhaps add more information (or log information) and then rethrow it
so that it bubbles up to a level where it can be deal with, or takes
the application down. That's fair. However, if you're not logging,
gathering more information, or morphin the exception into a more
meaningful exception, and there is nothing you can do about the
exception, then don't catch it. Just by catching it alone you haven't
"dealt with it": you just got your hands on it. You still have to
figure out what to do with it.

This is why C# didn't adopt Java's declared-exception methodology: it's
all too common in Java for programmers to catch exceptions because they
"have to" and then do nothing with them, because there's nothing they
can do. This effectively defeats the whole purpose of exceptions.

Now, this doesn't mean that whilst designing your methods, you
shouldn't think long and hard about which exceptions are possible and
whether (and how) you _could_ handle each one of them. The more
critical your code, the longer and harder you should think.

The only place where C# does not help you at all in this regard is that
there is no way (not even via FxCop) to detect exceptions that are
uncaught and undocumented. That is, if you don't catch an exception,
you should at least document in your method / property documentation
that your method or property can be a source of that uncaught
exception. However, there's no way to double-check this, and not even
Microsoft gets it right all the time. This, I think, is most
unfortunate.

Nov 17 '05 #25

P: n/a
Joseph Geretz <jg*****@nospam.com> wrote:
Basically, in our VB shop our policy is to always anticipate the possibility
of an unanticipated error. We're not going to impose any sort of flow
control in this case. Since the condition is fundamentally unanticipated
there's no way we can continue processing meaningfully. All we want to do is
get out of Dodge and return to the UI while collecting as much stack
information as we can along the way.

Does .NET exception mechanism do this natively for us? The information I'm
interested in having after the stack completely unwinds is:

A. Stack Trace (i.e. App.cmdSave_Click -> App.SaveUser ->
DataBroker.ExecSQL -> OLEDB.Whatever...)
Yes, you get that. (See the StackTrace property of Exception.)
B. Local variable values at various points in this stack trace (Simple
example, the variable UserID = 32768 might point me immediately to an
improperly sized column in the database, or an improperly defined variable
in code.)


No, you don't get that - but if you make sure that whenever your code
throws an exception itself (eg if it's detected that some method
parameters are invalid) it gives plenty of information, that's usually
enough. Some exceptions thrown by other libraries are informative like
that; others are less so. I very rarely find it's a problem though -
and not having to make *every* method have a catch block is a big win
in code readability terms.

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

P: n/a
Joseph Geretz <jg*****@nospam.com> wrote:
I agree that it's worthwhile to have the stack trace, but that doesn't
mean you need to catch the exception in each method. It'll still be
available if you just let it bubble up to the top level.
Will this include local variable values for each method on the stack, or
just the names of the methods themselves? If the trace will include local
variable then I'm certinaly looking forward to this new convenience!


The name of the method and the line number it was on (the latter only
if debug information is on).
If not though, then I guess its an improvement to capture the stack trace
natively, but I'd still like to have the local variable values for debugging
purposes. If this is not natively provided, then I'll need a covering catch
block in every method in order to capture local variable values at the time
of the exception.


I suggest you try doing it the simpler way for the moment - I bet
you'll save far more time by not having to decorate each method than
you'll lose through not having local variable information available -
especially if you make sure that wherever *you* throw a new exception,
you include a suitable message.

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

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote:
The idea that exceptions are truly expensive is a myth, however - if
you use exceptions reasonably, you're very, very unlikely to ever see
them become a performance problem.

See http://www.pobox.com/~skeet/csharp/exceptions.html


The very first exception thrown in an application can be fairly expensive,
though (at least in my experience).
Nov 17 '05 #28

P: n/a
Cool Guy <co*****@abc.xyz> wrote:
The idea that exceptions are truly expensive is a myth, however - if
you use exceptions reasonably, you're very, very unlikely to ever see
them become a performance problem.

See http://www.pobox.com/~skeet/csharp/exceptions.html


The very first exception thrown in an application can be fairly expensive,
though (at least in my experience).


It is *in the debugger* - but not outside the debugger in my
experience. Are you sure you've seen it being expensive when run
normally?

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

P: n/a
------------

Yes - but this is very different from having a catch block in every
method. Where you *can* recover and continue with a particular job of
work, of course it makes sense to catch exceptions - but I suspect
there aren't many applications where that translates to having an
exception handler in pretty much every method, as Joseph was talking
about.

------------

Yes, I agree, every method doesn't need exception handling. It's use
it to safeguard against potential, yet mostly predictable problems.

As I mentioned earlier, we use an ErrorHandler class we wrote that logs
exceptions we catch. Our concepts and standards evolve from our
environment. We handle government data, taxes, occupationl licenses,
etc. If we have an exception in the processing of something like that
we need to absolutely guarentee that it can be taken care of and that
it does not slip through the cracks.

We are working with a Partition Single Solution model. We have our top
level common library and work our way down to more specific libraries
and componants as the scope narrows down to the particular application.
Each sub-application, or child-environment, needs to interface with one
or more of the others - such as payments.

Because of this, we need to make sure that lower exceptions can be
trapped, logged, and otherwise handled on the spot to prevent potential
widespread problems. We cannot use the idea of, 'an exception
occurred, continue on, use finally to clean up regardless and let the
parent handle the childs mess'.

You can't possibly (as mentioned) hope to be able to catch every
exception, nor should you attempt to. But from the very beginning of
this thread I have simply said that it's better to avoid an exception
if at all possible; if not possible, might as well find a way to log
what happened (at least in our case, we need to know if a client
account has been potentially hosed).

Pretty much anything else in our environment is cosmetic and can be
alowed to bubble up as a general exception, in which case still gets
logged but does not set off any alarms. =)

Nov 17 '05 #30

P: n/a
BTW, regardless of the fact that (i think) we are all pretty much
splitting hairs here and arguing for the same thing, this has been a
pretty good thread. =)

Nov 17 '05 #31

P: n/a
Thanks Jon,
I suggest you try doing it the simpler way for the moment - I bet
you'll save far more time by not having to decorate each method than
you'll lose through not having local variable information available -
especially if you make sure that wherever *you* throw a new exception,
you include a suitable message.
Not having to decorate each method, would as you say, be a nice productivity
enhancement. It's fairly automatic to us by now, but it does take time.
Since a large portion of the information we're interested in (the Stack
Trace) comes natively, perhaps we can get by without capturing local
variables. I expect that we will shortly start to transition to .NET and
I'll keep your advice in mind when we formulate our error handling strategy.

Thanks!

- Joe Geretz

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... Joseph Geretz <jg*****@nospam.com> wrote:
> I agree that it's worthwhile to have the stack trace, but that doesn't
> mean you need to catch the exception in each method. It'll still be
> available if you just let it bubble up to the top level.


Will this include local variable values for each method on the stack, or
just the names of the methods themselves? If the trace will include local
variable then I'm certinaly looking forward to this new convenience!


The name of the method and the line number it was on (the latter only
if debug information is on).
If not though, then I guess its an improvement to capture the stack trace
natively, but I'd still like to have the local variable values for
debugging
purposes. If this is not natively provided, then I'll need a covering
catch
block in every method in order to capture local variable values at the
time
of the exception.


I suggest you try doing it the simpler way for the moment - I bet
you'll save far more time by not having to decorate each method than
you'll lose through not having local variable information available -
especially if you make sure that wherever *you* throw a new exception,
you include a suitable message.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 17 '05 #32

P: n/a
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote:
The very first exception thrown in an application can be fairly expensive,
though (at least in my experience).


It is *in the debugger* - but not outside the debugger in my
experience. Are you sure you've seen it being expensive when run
normally?


Ah, same here -- only expensive in the debugger. Didn't know that. :-)
Nov 17 '05 #33

P: n/a
gmiley <gm****@gmail.com> wrote:
Yes, I agree, every method doesn't need exception handling. It's use
it to safeguard against potential, yet mostly predictable problems.

As I mentioned earlier, we use an ErrorHandler class we wrote that logs
exceptions we catch. Our concepts and standards evolve from our
environment. We handle government data, taxes, occupationl licenses,
etc. If we have an exception in the processing of something like that
we need to absolutely guarentee that it can be taken care of and that
it does not slip through the cracks.


But how can you guarantee that you can always take care of things?
Given that exceptions are by their very nature unforeseen usually. You
seem to think I'm recommending ignoring problems when things go wrong.
That's absolutely not the csae - I'm recommending abandoning that
*attempt* to get the unit of work done, rolling it back, and then
either retrying immediately (from the start), retrying later, or adding
it to a separate queue of problem work items.

The area I work in is also very intolerant of losing data - please
don't assume that you're the only one who has absolute requirements in
this matter. I simply find that letting exceptions bubble up and going
back to square one is usually a better course than to try to patch an
already broken situation - especially when the symptoms of the
broken-ness often mask the actual cause.

<snip>

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

P: n/a
I understand what you are saying, but in a lot of cases it depends on
what exception is actually thrown as to what we need to do.

For instance:
Say a user has a customer come in that wants to pay their taxes, their
occupational licenses renewal and their vehicle registration renewal
all at once (some may be multiple items for each category).
If the items are added to the list of payments, and the customer says
"Hey ide like to pay for half with a check and half with my credit
card."

Now we have to split the amount of the items into equal portions - the
values are no longer directly tied with the original items, they pay
with the check and everything works fine - they pay with a credit card
and we get a TimeOutException on the authorization.

We need to make sure that doesn't just bubble up to the top end, we
need to log that there was a problem and deal with that. Just because
there was a time-out doesn't mean that the authorization failed (or
succeeded). There is a lot more work that needs to be done in a case
like this.

I know exactly what your saying when it comes to simple exceptions. But
in a lot of our personal cases we don't have simple exceptions that we
can just bubble up and tell the user "There was an error."

I've not been advocating the use of try/catch for every situation, just
trying to say that there are times when it is necessary to catch for
certain exceptions and let the others slide. The key is to analiyzing
your flow to see WHAT you need to possibly catch.

Nov 17 '05 #35

P: n/a
I guess I should add for clarity that we use a third party credit card
processing company (most do), they provide their own libraries that do
have a ProcessState, but while it is processing it will throw a
ProccessTimeoutException ... =( We can't let that go back up directly,
until we make a log entry and notify accounting that this particular
transaction may have a problem - in the event of a timeout, we do the
processing to log and notify then return back saying there was a
problem with the transaction, yadda yadda yadda, the cashier can then
re-try the authorization or accept an alternate method of payment.

Accounting then has the responsability to void the rogue transaction
payment.

Nov 17 '05 #36

P: n/a
I just want to thank all of those whose comments helped put this matter into
perspective.

<%= Clinton Gallagher

"clintonG" <cs*********@REMOVETHISTEXTmetromilwaukee.com> wrote in message
news:ez**************@TK2MSFTNGP14.phx.gbl...
Has somebody written any guidelines regarding how to determine when
try-catch blocks should be used and where their use would or could be
considered superfluous?

<%= Clinton Gallagher
METROmilwaukee (sm) "A Regional Information Service"
NET csgallagher AT metromilwaukee.com
URL http://metromilwaukee.com/
URL http://clintongallagher.metromilwaukee.com/

Nov 17 '05 #37

P: n/a
gmiley <gm****@gmail.com> wrote:
I understand what you are saying, but in a lot of cases it depends on
what exception is actually thrown as to what we need to do.

For instance:
Say a user has a customer come in that wants to pay their taxes, their
occupational licenses renewal and their vehicle registration renewal
all at once (some may be multiple items for each category).
If the items are added to the list of payments, and the customer says
"Hey ide like to pay for half with a check and half with my credit
card."

Now we have to split the amount of the items into equal portions - the
values are no longer directly tied with the original items, they pay
with the check and everything works fine - they pay with a credit card
and we get a TimeOutException on the authorization.

We need to make sure that doesn't just bubble up to the top end, we
need to log that there was a problem and deal with that. Just because
there was a time-out doesn't mean that the authorization failed (or
succeeded). There is a lot more work that needs to be done in a case
like this.
In a very few cases, that's reasonable - but it should usually be the
exception (no pun intended) rather than the norm.
I know exactly what your saying when it comes to simple exceptions. But
in a lot of our personal cases we don't have simple exceptions that we
can just bubble up and tell the user "There was an error."

I've not been advocating the use of try/catch for every situation, just
trying to say that there are times when it is necessary to catch for
certain exceptions and let the others slide. The key is to analiyzing
your flow to see WHAT you need to possibly catch.


That I'd certainly agree with - but you wrote before:

<quote>
Because of this, we need to make sure that lower exceptions can be
trapped, logged, and otherwise handled on the spot to prevent potential
widespread problems.
</quote>

That suggests you're trying to handle (rather than let bubble up)
*every* lower level exception, which still seems wrong to me.

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

This discussion thread is closed

Replies have been disabled for this discussion.