473,387 Members | 1,724 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,387 software developers and data experts.

Try and Catch VS Regular Defensive Programming

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?


What is best "practices" in relation to Try + Catch VS Defensive Programming
in general?
Nov 20 '05 #1
6 5027
Hi,

To supplement regular defensive programming as you describe it AND to deal
with catastrophic events. 'If exists' etc really don't call for try catch
anymore than it would call for 'on error resume next' in vb 6.

HTH,

Bernie Yaeger

"Martin Ortiz" <ma*********@optonline.com> wrote in message
news:ex**************@TK2MSFTNGP09.phx.gbl...
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?

What is best "practices" in relation to Try + Catch VS Defensive Programming in general?

Nov 20 '05 #2
In my opinion, Matin, it's a matter of personal choice and style.

There are times when Try ... Catch can be considered as 'regular defensive
programming', and there are times when Try ... Catch is redundant.

"Martin Ortiz" <ma*********@optonline.com> wrote in message
news:ex**************@TK2MSFTNGP09.phx.gbl...
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?

What is best "practices" in relation to Try + Catch VS Defensive Programming in general?

Nov 20 '05 #3
Cor
Martin,
I should not use it for a divide by zero which you can prevent in other
ways.

But to catch if someone has disconnected something is a nice thing to
prevent that the customer is not direct pointing to the program.

I think it's something in between that.
Cor
Nov 20 '05 #4
Hello,

"Martin Ortiz" <ma*********@optonline.com> schrieb:
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?


If a method throws an exception, you may want to handle it somewhere. If it
only returns a boolean value telling you if it has done its work
successfully, you don't need a 'Try...Catch' handler. Notice that using
error handling slows down your application.

--
Herfried K. Wagner
MVP · VB Classic, VB.NET
<http://www.mvps.org/dotnet>
Nov 20 '05 #5
Hi Martin,

The (very) short answer: Try...Catch should be used wherever you expect an
exception and you either *know* how to handle that exception or you *need*
to handle that exception.

The (very) long answer:

It's first worth discussing here a subtle distinction in terminology.
Exceptions and errors aren't synonymous; in other words, they're different
creatures. Exceptions can be used to signal errors (such as division by
zero), unexpected events (for instance, the printer running out of paper),
and violations of an interface's assumptions (for example, passing a
parameter with a negative value when the interface expects a positive
value). Although each of these three exceptions could be called an error
from the point of view of the method that throws the exception, it's the
developer writing the code calling the method who really knows what he or
she expects and who therefore defines which of these exceptions is actually
an error from the point of view of the application as a whole.

For example, a method that performs a printing task might throw an exception
because the printer is out of paper, but if the code that calls that method
has been programmed correctly, this would be an expected event, not an error
at all. The exception would just be passed up the call stack before being
transformed into a message asking the user to place some more paper in the
printer.

This distinction is important because when you design a method or class, you
need to decide how you're going to communicate information to the calling
method and which exceptions you're going to throw. Say that you've been
given the task of designing and implementing a class that validates a user
login to an application. In the method that validates the user login, should
an exception be thrown when the login fails or should the method return a
value of false instead?

There is no correct answer to this question. Some developers maintain that a
login failure is an error and therefore an exception should be thrown. Other
developers reason that a login failure is an expected event and not really
an error as far as the application is concerned, therefore the method should
return a status variable rather than forcing the calling code to handle an
exception. Although in this situation I favour returning a status variable
and not throwing an exception, you and your team will have to decide for
yourselves how you are going to handle these design decisions.

One point to bear in mind when making these types of decisions is that you,
as a designer of a method or class, often don't know what the code that
calls your method considers to be an error. If, for instance, you're
developing a method that reads information from a file on disk, how should
you signal that the calling method has read past the end of the file? Is
reading past the end of the file an error or not? Because you don't know
what the calling code is doing, you just don't know whether this is an
error. In this situation, I would throw an exception because I just can't
tell whether the calling code expected to read past the end of the disk
file. Another developer might maintain that reading past the end of a file
is always a possible occurrence as far as most calling code is concerned,
and therefore he would design the method to return a EOF status flag rather
than throw an exception.

Try...Catch should also be used for the following three situations:

1) You want to throw a custom exception rather than the exception that was
thrown. For instance, you might want to signal an error or unexpected event
that isn't described adequately by an existing exception. Or you don't want
to confuse the developer calling your component with an exception thrown by
a component below yours. Finally, you might want to wrap an existing
exception to provide extra information.

2) You want to execute some recovery code. For example, you need to reverse
a transaction that failed before it completed. This strategy can involve
swallowing the original exception or rethrowing it, depending on circumstanc
es.

3) You want to execute some cleanup code. For instance, you need to clean up
after an exception by closing a file or database connection. Once again, you
might want to swallow the original exception or rethrow it, depending on
circumstances.

Apart from these situations, you should let exceptions bubble upwards until
they reach your user interface (if you have one) or your unhandled
(last-chance) exception handler. If it reaches your user interface, you
should catch the exception and display a helpful context-sensitive message
to the end-user. If it reaches your unhandled exception handler, you should
catch the exception and log it somewhere.

HTH,

Mark
--
Author of "Comprehensive VB .NET Debugging"
http://www.apress.com/book/bookDisplay.html?bID=128
"Martin Ortiz" <ma*********@optonline.com> wrote in message
news:ex**************@TK2MSFTNGP09.phx.gbl...
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?


What is best "practices" in relation to Try + Catch VS Defensive Programming
in general?

Nov 20 '05 #6
thanks for the helpful pointers...
Mark
Author of "Comprehensive VB .NET Debugging" <--- hah! explains the comprehensive post! :-)

"Mark Pearce" <ev**@bay.com> wrote in message
news:ud*************@TK2MSFTNGP10.phx.gbl... Hi Martin,

The (very) short answer: Try...Catch should be used wherever you expect an
exception and you either *know* how to handle that exception or you *need*
to handle that exception.


Nov 20 '05 #7

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

Similar topics

11
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill...
22
by: STom | last post by:
I heard someone mention to me that the use of try catch exception handling is very expensive (in relative terms of slowing an app down) if it is used frequently. Of course they could not explain...
11
by: Tantr Mantr | last post by:
I want to convert a string to a DateTime type. The user can enter the date in various formats and I am not sure if it will be a valid Date. Is it possible to check if a string can be converted to a...
20
by: Asper Faner | last post by:
I seem to always have hard time understaing how this regular expression works, especially how on earth do people bring it up as part of computer programming language. Natural language processing...
6
by: rhaazy | last post by:
I am looking for some feedback on using try catch statements. Usually when I start a project I use them for everything, but stop using them as often after the "meat n' potatos" of the project is...
32
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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.