473,654 Members | 3,060 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Try and Catch VS Regular Defensive Programming

Which is best approach?
Should Try + Catch be used to only deal with "catastroph ic" 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 5042
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*********@op tonline.com> wrote in message
news:ex******** ******@TK2MSFTN GP09.phx.gbl...
Which is best approach?
Should Try + Catch be used to only deal with "catastroph ic" 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*********@op tonline.com> wrote in message
news:ex******** ******@TK2MSFTN GP09.phx.gbl...
Which is best approach?
Should Try + Catch be used to only deal with "catastroph ic" 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*********@op tonline.com> schrieb:
Should Try + Catch be used to only deal with "catastroph ic"
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 "Comprehens ive VB .NET Debugging"
http://www.apress.com/book/bookDisplay.html?bID=128
"Martin Ortiz" <ma*********@op tonline.com> wrote in message
news:ex******** ******@TK2MSFTN GP09.phx.gbl...
Which is best approach?
Should Try + Catch be used to only deal with "catastroph ic" 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 "Comprehens ive VB .NET Debugging" <--- hah! explains the comprehensive post! :-)

"Mark Pearce" <ev**@bay.com > wrote in message
news:ud******** *****@TK2MSFTNG P10.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
6884
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 non-supporting browsers? TIA -- --
22
3363
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 why. Is this true? If so, why? Thanks. STom
11
4631
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 DateTime type without using a try / catch block. I was thinking of maybe something like is or as commands. But both do not seem to work for this. Any suggestions will be much appreciated. Right now i have : string s = "01/05/2006"; //user will...
20
416
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 seems not enough to explain by the way. Why no eliminate it ?
6
1512
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 finished. I am thinking it would be useful to at least have a blanket try-catch to surround all of the code, and add more to aid in debugging and catching specific exceptions. I want to change my habits but before I do I wanted to see if anyone...
32
2065
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
8379
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
8294
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8596
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6162
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
5627
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
4150
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
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2719
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1597
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.