473,769 Members | 2,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Defensive Programming - Where do you Draw the Line?

Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?

The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to add
error handling, assertions, and other validation code?

The bigger picture is this: I'm rewriting a few utilities that I wrote a few
years ago. They have been humming along just fine in production. As part of
my current refactoring-from-1.1-to3.5 effort... in addition to adding a few
new capabilities, I'm wanting to make things more "bullet proof" - not out
of necessity (such tasks would have been done by now), but more for the sake
of doing it "right" or at least better. So I look at the above and think
that it's so incredibly unlikely that anything would ever go wrong with
that - so is there any reason to add the extra code - little as it may be -
for a try... catch block.

And yes, I know "it all depends" [on usage context, etc] - but I'd
appreciate your additional thoughts beyond that.

Do any of you actually put at least one try... catch block in *every* method
you ever write? If not, when do you NOT put one in for reasons other than
laziness?

Thanks.
Oct 2 '07 #1
9 1901
Smithers <A@B.comwrote :
Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?

The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to add
error handling, assertions, and other validation code?
I write very few try/catch blocks. I write far more try/finally blocks,
usually implicitly with "using" statements. Well-written error-handling
code *tends* to be at a very high level, indicating that something
within a potentially very deep stack has failed. There's often no need
to handle the error other than at the top level.
The bigger picture is this: I'm rewriting a few utilities that I wrote a few
years ago. They have been humming along just fine in production. As part of
my current refactoring-from-1.1-to3.5 effort... in addition to adding a few
new capabilities, I'm wanting to make things more "bullet proof" - not out
of necessity (such tasks would have been done by now), but more for the sake
of doing it "right" or at least better. So I look at the above and think
that it's so incredibly unlikely that anything would ever go wrong with
that - so is there any reason to add the extra code - little as it may be -
for a try... catch block.
What would you even do in the catch block? You can't really recover
from the error. The best you could do is log and then rethrow - but in
that case, you might as well catch at the top level and log there.
Do any of you actually put at least one try... catch block in *every* method
you ever write? If not, when do you NOT put one in for reasons other than
laziness?
It should be the other way round - if your method fails to execute,
what good reason do you have for *not* just letting the exception
bubble up? How are you going to add value to that error-reporting
mechanism? Can you recover from the error?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 2 '07 #2
Smithers wrote:
Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?
I agree with Jon's reply. Don't catch an exception unless either a) you
have some cleanup you need to do, or b) you can actually gracefully
recover from the exception.

This means that most code doesn't have any exception handling.

In your specific example, it's not clear what those identifiers are.
However, the naming convention is one usually reserved for fields. It's
not clear to me how the code could throw an exception anyway, but
perhaps you've just left out some specific information about the
identifiers (maybe they are properties that do something more than just
setting a value type?).

However, even if the assignments could throw exceptions, the question is
begged: what would you do in the exception handler? How could you
gracefully recover from an error? The caller certainly will assume that
the counters have been successfully reset when the function returned; if
you catch the exception and return normally, you've now put your program
into some unexpected, if not completely invalid, state.
The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to add
error handling, assertions, and other validation code?
Whether to write an exception handler depends on whether you can or must
do something useful in handling the exception, not with respect to how
likely exception is.
The bigger picture is this: I'm rewriting a few utilities that I wrote a few
years ago. They have been humming along just fine in production. As part of
my current refactoring-from-1.1-to3.5 effort... in addition to adding a few
new capabilities, I'm wanting to make things more "bullet proof" - not out
of necessity (such tasks would have been done by now), but more for the sake
of doing it "right" or at least better.
"Bullet-proofing" is a fine goal. However, you have to be sure that you
are really bullet-proofing. Sweeping errors under the rug by writing
exception handling that doesn't actually do anything doesn't
bullet-proof anything; it just defers the problem to some later,
more-difficult-to-analyze point.
So I look at the above and think
that it's so incredibly unlikely that anything would ever go wrong with
that - so is there any reason to add the extra code - little as it may be -
for a try... catch block.
Well, again...in that specific example, how could an exception occur?
And yes, I know "it all depends" [on usage context, etc] - but I'd
appreciate your additional thoughts beyond that.

Do any of you actually put at least one try... catch block in *every* method
you ever write? If not, when do you NOT put one in for reasons other than
laziness?
I definitely do _not_ put at least one try/catch block in every method.
The vast majority of methods in my code do not include any exception
handling at all. In my own code, the only place you'll ever see an
exception handling block is where I can actually respond to the
exception in a useful way. Sometimes this is just a matter of cleaning
up and letting the exception continue up the call stack (using or
try/finally) and sometimes this is a matter of detecting and recovering
from an error.

Pete
Oct 2 '07 #3
On Oct 2, 2:02 pm, "Smithers" <A...@B.comwrot e:
Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;

}

Given no further information, would you wrap those two lines in a try...
catch block?

The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to add
error handling, assertions, and other validation code?

The bigger picture is this: I'm rewriting a few utilities that I wrote a few
years ago. They have been humming along just fine in production. As part of
my current refactoring-from-1.1-to3.5 effort... in addition to adding a few
new capabilities, I'm wanting to make things more "bullet proof" - not out
of necessity (such tasks would have been done by now), but more for the sake
of doing it "right" or at least better. So I look at the above and think
that it's so incredibly unlikely that anything would ever go wrong with
that - so is there any reason to add the extra code - little as it may be -
for a try... catch block.

And yes, I know "it all depends" [on usage context, etc] - but I'd
appreciate your additional thoughts beyond that.

Do any of you actually put at least one try... catch block in *every* method
you ever write? If not, when do you NOT put one in for reasons other than
laziness?

Thanks.
Hi Smithers,
No I would not put a try block in that routine. I don't see the point
to it (what would you do in a catch or finally block?). Basically,
put a try block where you need to do something in either the finally
or catch blocks. If you can't think of code you would put in a
finally or catch block (I can't for your sample code) then that's a
good hint that you don't need it.

My feeling is that you can make your code more bulletproof by
liberally adding check code that *throws* more exceptions (or does
more debug Asserts), which will help you identify situations where the
data isn't what you'd expect (making sure objects are not null,
verifying values are within range, etc...). The further upstream you
find the error, the easier it is to debug your problem. I've seen a
lot of code that just exits the method if an unexpected condition is
encountered, but that just sweeps the problem further downstream.

Also I agree with Jon's comment that exceptions in general should be
allowed to bubble up to a top-level (or higher-level) exception
handler... it's usually where you have the most context to do
something anyways (show message to user, etc...)
John

Oct 2 '07 #4
"Smithers" <A@B.comwrote :
Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?
I would continue allowing this to be a humble method, just as it's written.

As Jon said, even if you put in a try/catch, what would you do here? There's
just no point.

The whole point of Exception handling is that every method doesn't have a
try/catch. If it did, it would be no better than (or even worse than) "On
Error Resume Next" or some other horrible error handling mechanism.
Do any of you actually put at least one try... catch block in *every*
method you ever write?
Hell no! If I saw code that did this, I would spend the rest of the day
"educating" the original developer, and then stand over his shoulder all
week long as he rips it all out.
If not, when do you NOT put one in for reasons other than laziness?
In general:
- put try/catch blocks at high levels in your code, where they can actually
do something. Sometimes "something" is defined as "log the error + [Continue
| Exit | Alert]."
- put try/catch blocks at places in your code where you can actually handle
the error.

--
Chris Mullins
Oct 2 '07 #5

I concur

try
{

}
finally
{

}

blocks should exist in your code ALOT more than
try/catch or try/catch/finally blocks.

Brad Abrams talked about this as well when he visited our UserGroup

http://msdn2.microsoft.com/en-us/lib...05(VS.80).aspx
//Quote//
Do use try-finally and avoid using try-catch for cleanup code. In
well-written exception code, try-finally is far more common than try-catch.
The purpose of a catch clause is to allow you to handle exceptions (for
example, by logging a non-fatal error). The purpose of a finally clause is
to allow you to execute cleanup code regardless of whether an exception was
thrown. If you allocate expensive or limited resources such as database
connections or streams, you should put the code to release them inside a
finally block.

"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Smithers <A@B.comwrote :
>Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?

The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to
add
error handling, assertions, and other validation code?

I write very few try/catch blocks. I write far more try/finally blocks,
usually implicitly with "using" statements. Well-written error-handling
code *tends* to be at a very high level, indicating that something
within a potentially very deep stack has failed. There's often no need
to handle the error other than at the top level.
>The bigger picture is this: I'm rewriting a few utilities that I wrote a
few
years ago. They have been humming along just fine in production. As part
of
my current refactoring-from-1.1-to3.5 effort... in addition to adding a
few
new capabilities, I'm wanting to make things more "bullet proof" - not
out
of necessity (such tasks would have been done by now), but more for the
sake
of doing it "right" or at least better. So I look at the above and think
that it's so incredibly unlikely that anything would ever go wrong with
that - so is there any reason to add the extra code - little as it may
be -
for a try... catch block.

What would you even do in the catch block? You can't really recover
from the error. The best you could do is log and then rethrow - but in
that case, you might as well catch at the top level and log there.
>Do any of you actually put at least one try... catch block in *every*
method
you ever write? If not, when do you NOT put one in for reasons other than
laziness?

It should be the other way round - if your method fails to execute,
what good reason do you have for *not* just letting the exception
bubble up? How are you going to add value to that error-reporting
mechanism? Can you recover from the error?

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

Oct 2 '07 #6
The "humble method" in the OP here is setting field values.

The reason for the OP is that I have heard a lot of advice over the years
about what we should or should not do under the guise of "best practice" or
"defensive programming" etc. One of those pieces of advice is "every method
should have a try/catch block". I've never done it, and for reasons similar
to those pointed out already in this thread. So I was just wondering what
some of you think about it.

I cannot provide a source for that particular piece of advice regarding
try/catch. But I have heard it and it has bothered me for a while... causing
me to wonder if I was missing something.Anoth er such piece of advice which I
don't get is from Juval Lowy which states "Assert every assumption. On
average every fifth line is an assertion." That's #14 in his
self-proclaimed defacto C# coding standards list (available at
www.idesign.net).

It seems to me that if we were to follow *every* "best practice" and piece
of advice at the same time, then our code would be at least huge, probably
unreadable, and would possibly break.

To digress just a bit (but for purposes of analogy), I was recently in
Canada and they had a HUGE health food store. It was about 3000 sq ft of
health supplements, remedies, vitamins, minerals, organic this, and organic
that. Pine nut oil. Flax seed extract. Every aisle crammed with stuff I'd
never heard of before. I couldn't help but think that (1) for every single
product in there, somebody swears by it; (2) mankind has gotten along just
fine without all this stuff for all time up 'til now; and (3) if I were to
take one of everything in the store I'd probably die within hours if not
minutes. When I first saw that tiny bottle of pine nut oil I couldn't help
but think about Juval Lowy's advice to test *every* assumption and write an
assertion into every 5th line on average.

-S


"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:13******** *****@corp.supe rnews.com...
Smithers wrote:
>Please consider this humble method:

public void ResetCounters()
{
m_TotalExceptio nsDetected = 0;
m_TotalMessages Sent = 0;
}

Given no further information, would you wrap those two lines in a try...
catch block?

I agree with Jon's reply. Don't catch an exception unless either a) you
have some cleanup you need to do, or b) you can actually gracefully
recover from the exception.

This means that most code doesn't have any exception handling.

In your specific example, it's not clear what those identifiers are.
However, the naming convention is one usually reserved for fields. It's
not clear to me how the code could throw an exception anyway, but perhaps
you've just left out some specific information about the identifiers
(maybe they are properties that do something more than just setting a
value type?).

However, even if the assignments could throw exceptions, the question is
begged: what would you do in the exception handler? How could you
gracefully recover from an error? The caller certainly will assume that
the counters have been successfully reset when the function returned; if
you catch the exception and return normally, you've now put your program
into some unexpected, if not completely invalid, state.
>The above is a specific example of a more general question... when an
exception is incredibly unlikely to occur, is there any good reason to
add error handling, assertions, and other validation code?

Whether to write an exception handler depends on whether you can or must
do something useful in handling the exception, not with respect to how
likely exception is.
>The bigger picture is this: I'm rewriting a few utilities that I wrote a
few years ago. They have been humming along just fine in production. As
part of my current refactoring-from-1.1-to3.5 effort... in addition to
adding a few new capabilities, I'm wanting to make things more "bullet
proof" - not out of necessity (such tasks would have been done by now),
but more for the sake of doing it "right" or at least better.

"Bullet-proofing" is a fine goal. However, you have to be sure that you
are really bullet-proofing. Sweeping errors under the rug by writing
exception handling that doesn't actually do anything doesn't bullet-proof
anything; it just defers the problem to some later,
more-difficult-to-analyze point.
>So I look at the above and think that it's so incredibly unlikely that
anything would ever go wrong with that - so is there any reason to add
the extra code - little as it may be - for a try... catch block.

Well, again...in that specific example, how could an exception occur?
>And yes, I know "it all depends" [on usage context, etc] - but I'd
appreciate your additional thoughts beyond that.

Do any of you actually put at least one try... catch block in *every*
method you ever write? If not, when do you NOT put one in for reasons
other than laziness?

I definitely do _not_ put at least one try/catch block in every method.
The vast majority of methods in my code do not include any exception
handling at all. In my own code, the only place you'll ever see an
exception handling block is where I can actually respond to the exception
in a useful way. Sometimes this is just a matter of cleaning up and
letting the exception continue up the call stack (using or try/finally)
and sometimes this is a matter of detecting and recovering from an error.

Pete

Oct 2 '07 #7
Chris Mullins [MVP - C#] <cm******@yahoo .comwrote:
It's funny, but I've always disliked the Try/Finally syntax. I may be the
only one, but... ick.
I don't mind the syntax for try/finally when "using" doesn't do the
job, but when "using" is available it's clearly neater. I very rarely
write "manual" finally clauses in C#.

I *do* wish that you could add a "catch" clause to "using" though:

using (...)
{
}
catch (WebException we)
{
....
}

could convert to:

try (...)
{
}
catch (WebException we)
{
....
}
finally
{
// Dispose
}

When you *do* want to catch exceptions in addition to using a "using"
statement, the extra level of nesting reduces the readability somewhat.

IMO, anyway...

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Oct 2 '07 #8
Jon Skeet [C# MVP] wrote:
I write very few try/catch blocks. I write far more try/finally blocks,
usually implicitly with "using" statements. Well-written error-handling
code *tends* to be at a very high level, indicating that something
within a potentially very deep stack has failed. There's often no need
to handle the error other than at the top level.
I agree.

One of the biggest (maybe the biggest) advantage of the exception
concept is the ability to automatically send the info up the call
stack without a zillion tests on return values.

If exceptions were always to be caught where they happened we
could (almost) as well use return values. Exceptions are intended
to be caught high up in the call stack where there may be code that
has a chance of doing something reasonable to handle the exception.

I have seen application designs where there were an explicit
design rule that the N top layers was required to catch
exceptions and the M bottom layers was forbidden to catch exceptions
(layers is here in the high specific - low general sense).

Of course there are cases where the rule is not optimal, but it is
a consistent approach that a developer team can understand.

Arne
Oct 2 '07 #9

"Smithers" <A@B.comwrote in message
news:e3******** ******@TK2MSFTN GP05.phx.gbl...
The "humble method" in the OP here is setting field values.

The reason for the OP is that I have heard a lot of advice over the years
about what we should or should not do under the guise of "best practice"
or "defensive programming" etc. One of those pieces of advice is "every
method should have a try/catch block". I've never done it, and for reasons
similar
This is absolutely wrong. Every return value should be checked and error
propagated. Exceptions are an automated way of doing that (with additional
efficiency improvements using long jumps internally instead of masses of
conditionals and return statements). Exceptions are designed to solve the
same problem as return error codes, but they must not be treated as error
codes.

Any well-designed program uses a mix of exceptions and failure codes. (A
failure isn't an error if it is anticipated). For example, it is
appropriate to have List.Find return a failure code instead of an exception,
because calling List.Contains first to avoid an exception would require
iterating the List twice.
Oct 2 '07 #10

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

Similar topics

8
2394
by: Todd Smith | last post by:
I'm wondering if anyone knows where I can learn a good programming method for creating windows apps. I'm just starting to learn windows programming with MSVC++ 6.0. I want to learn low level windows programming in C first. I don't want to learn any bad habits by hacking away at code until I get something to work. Specifically, I'd like to learn how to set up and plan out a C windows project and break it down into pieces of code that will...
1
5616
by: Scott Chang | last post by:
Hi All I tried to use the attached OpenGL code to draw a Star-shaped figure on my Microsoft Visual C++ .NET 2002-Windows XP Pro PC. When I did 'Build' in Debug Mode, I got an error C2065: 'RenderScence': undeclared identifier. Please help and tell me (1) what it is wrong with my coding in this program and how to correct the problem, and (2) whether the functions/commands of the OpenGL v1.1 (existing in Microsoft Visual C++ .NET 2002) and GLUT...
6
5052
by: Martin Ortiz | last post by:
Which is best approach? Should Try + Catch be used to only deal with "catastrophic" events (like divide by zero, non-existant file, etc...etc...) Or should Try + Catch be used IN PLACE of regular defensive programming? (ie if file exists do this, if not do something else) Or should Try + Catch be used TO SUPPLAMENT regular defensive programming?
2
3136
by: dan heskett | last post by:
I am owner-drawing a listbox, in an attempt to create a nice list with some custom "fields" and text layout. Essentially it works, but I must be missing something big, conceptually, because I get all kinds of screen artifacts and weirdness. My general goal is: list item with a few areas for text, every other item shaded a light color for readability, font color changes with selection. The listbox is populated with custom structurs...
111
5590
by: Enteng | last post by:
Hi I'm thinking about learning C as my first programming language. Would you recommend it? Also how do you suggest that I learn it?What books/tutorials should I read for someone like me? Thanks in advance! -entengk
9
4028
by: zhaow | last post by:
Hi, All Greetings! I want to develop as appllication that requires a line-drawing function in the blank area between two forms. I have looked up the MSDN, it says that a graphics object need a reference to a control or a form. I guess it means that lines can't be draw on blank area between two forms. Can anybody guarantee this for me? Is there any method can realize this function? I mainly want to draw a line from a button in form1 to...
8
1998
by: Lamefif | last post by:
// C3DRect supports IDraw and IShapeEdit. class C3DRect : public IDraw, public IShapeEdit { public: C3DRect(); virtual ~C3DRect(); // IDraw virtual void Draw(); // IShapeEdit virtual void Fill (FILLTYPE fType);
47
2296
by: neha_chhatre | last post by:
#include <math.h> #include <stdio.h> float log(float num); double log(double num); long double log(long double num); int main()
32
2090
by: bingfeng | last post by:
hello, please see following two code snatches: 1. int foo (const char* some) { assert(some); if (!some) { return -1; //-1 indicates error }
0
9586
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10210
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.