473,625 Members | 2,615 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Tip on error handling and DAO reference cleanup

When writing VB or VBA code that works with databases or other external
libraries that cannot be trusted to automatically do the right thing when
references to their objects are arbitrarily released, some thought must be put
into how to make sure the objects will all be closed and released in the
correct order, even in the result of an error.

This requirement can make our code really ugly, even following the best of
commonly known best practices.

For instance, technically, the only procedures that should be -required- to
have their own error handlers are procedures triggered by UI events, and those
that must take specific action in response to specific errors. All of our DAO
code, though, requires a clean-up block though, and custom error handling that
either duplicates that logic or resumes to a point just before the clean-up
happens. If the calling code should ultimately be responsible for reporting
and/or logging the error, now we actually have to raise the error again so
that code can respond.

Now, we may find ourselves repeatedly writing code to do things like set up
the database reference, create a Querydef, open a recordset, do one useful
thing, then close the recordset, etc., all with massive setup/teardown
overhead - yuck. In many cases, then, a simple procedure can take 2 screens
worth of code, and most of it has nothing to do with the primary purpose of
the procedure. Code becomes unduely hard to read and maintain. In fact, to
keep code simpler then, we frequently skip using querydefs and parameters when
they would be useful or improve robustness.

Enter custom class modules.

Unlike classes in external libraries, we do have control over what happens
when instances of our custom classes are terminated, and unlike
garbage-collector based languages such as Java, we know that any terminate
procedures will run when the last reference to the object goes out of scope.
The key point here is that this is true even if the reference goes out of
scope when the procedure that referenced it raises an error that pops control
back to a calling procedure!

So - the trick is to make a class that does nothing more than handle the
running queries. This includes maintaining a database, a querydef, and
optionally, a recordset (if the query is a select query). The class also
keeps track of whether it got its database reference by explicitly opening it
(as opposed to being given one, or using CurrentDb to get one), so it knows if
it will be responsible for closing it.

When the class instance terminates, it first closes the recordset if one is
open, releases the recordset, releases the querydef, closes the database if it
is responsible for doing so, then releases the database reference. Notice
that now the calling code needs no direct references to the 3 DAO objects, nor
does it need to clean them up, or include custom error handling if it doesn't
otherwise need to. Also notice how simple the classs can be since it doesn't
need any internal error handling to speak of.

A class like this can easily be under 100 lines long, save you 1000s of lines
elsewhere, and relieve the stress of repeatedly fussing over DAO object setup
and teardown.

Note that this is also useful for ADO even though we have a higher trust in
its ability to handle dropped references. First of all, we don't have 100
percent trust because we've been burned by DAO and other libraries. Second,
the process of adding parameters to an ADO Command object can be arduous, and
our wrapper class is a great place to put a simplified procedure call for
adding such parameters.
Nov 13 '05 #1
2 3008
Steve Jorgensen wrote:
Enter custom class modules.


Thank you for the tip. Even when we have no particular use for a tip,
reading it can prompt us to review our own practises and, perhaps,
modify them. I think CDMA would be better if each of the regulars
(others too if they wished) took a few minutes to post new procedures,
methods, whatever we are trying, ideas even, from time to time.

--
--
Lyle
--
Nov 13 '05 #2
On Wed, 16 Mar 2005 12:26:18 -0500, Lyle Fairfield <ly******@yahoo .ca> wrote:
Steve Jorgensen wrote:
Enter custom class modules.


Thank you for the tip. Even when we have no particular use for a tip,
reading it can prompt us to review our own practises and, perhaps,
modify them. I think CDMA would be better if each of the regulars
(others too if they wished) took a few minutes to post new procedures,
methods, whatever we are trying, ideas even, from time to time.

--
--
Lyle


You're probably right. In fact, I'll bet you have some good tips to offer...
:)
Nov 13 '05 #3

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

Similar topics

12
3677
by: Ritz, Bruno | last post by:
hi in java i found that when a method has a throws clause in the definition, callers must either handle the exceptions thrown by the method they are calling or "forward" the exception to the caller by specifying a throws clause as well. is there a similar machanism in c++? i want to force a developer to write handlers for all possible exceptions a method of my class library can throw.
5
1719
by: John Perks and Sarah Mount | last post by:
When handling resources in Python, where the scope of the resource is known, there seem to be two schools of thought: (1) Explicit: f = open(fname) try: # ... finally: f.close()
6
8449
by: Squirrel | last post by:
I have a command button on a subform to delete a record. The only statement in the subroutine is: DoCmd.RunCommand acCmdDeleteRecord The subform's recordsource is "select * from tblVisit order by VisitDt" I'm getting this error message: Errno is 2465. Err.description is "Can't find field '|' referred to in your expression"
4
1986
by: Sandy | last post by:
Hello - I read an interesting article on the web wherein the author states he doesn't handle too many errors at page level, but handles them at the application level. He further goes on to show how error logging can be incorporated using a Sql Server log with an additional text log in case Sql Server was down. My inclination after reading the article is to use Try-Catch-Finally as little as possible (tends to slow things if you have...
8
1784
by: jcrouse | last post by:
I am using the following code to trap errors in a sub routine: Try Executable code Catch ex As Exception Dim strInputE As String = Application.StartupPath & "\Error.txt" Dim srE As StreamWriter = File.AppendText(strInputE) srE.WriteLine(vbCr) srE.WriteLine(vbCr) srE.WriteLine(DateTime.Now)
3
372
by: dgiagio | last post by:
Hi, I'm creating a SMTP application and I would like to hear opinions about error handling. Currently there are two functions that communicate with the remote peer: ssize_t smtp_puts(smtp_stream_t *stream, const char *fmt, ...); ssize_t smtp_gets(smtp_stream_t *stream, char *buf, size_t len); Both of them return the number of written bytes to the stream, or -1 if
0
3705
by: ruju00 | last post by:
I am getting an error in Login() method of the following class FtpConnection public class FtpConnection { public class FtpException : Exception { public FtpException(string message) : base(message){} public FtpException(string message, Exception innerException) : base(message,innerException){}
4
1966
by: John Wright | last post by:
I need some good ideas or references for robust error handling in VB.NET. I am using try catch but find myself using the generic exception handler. I would like to get more precise error handling so I can take appropriate action and display user friendly error messages back to the client. The problem I am getting is determining which error types can be thrown for each function/sub and handling them. Is there a way to determine all the...
35
3770
by: jeffc226 | last post by:
I'm interested in an idiom for handling errors in functions without using traditional nested ifs, because I think that can be very awkward and difficult to maintain, when the number of error checks gets about 3 or so. It also gets very awkward in nested loops, where you want to check for normal loop processing in the loop condition, not errors. Yes, you could put some generic exit flag in the loop condition, but when you're simply done if...
0
8251
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
8182
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
8688
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...
0
7178
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5570
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
4188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2614
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
1
1800
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1496
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.