473,624 Members | 2,191 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help me understand try-catch

Hi all,

I'm trying to understand the best way to use a try catch with a SQL
transaction. I have a number of sql statements that need to be run, such
as:

'open sqlConnection, get command object, etc.
myTrans.BeginTr ansaction()
'do a delete
'do a update
'do an insert
myTrans.Commit( )
'close connection/dispose of objects

However, I want to be able to roll it back so I do

myTrans.BeginTr ansaction()
Try
'do a delete
'do a update
'do an insert
catch ex as exception
myTrans.RollBac k()
throw new exception("ERRO R!",ex)
finally
'close connection/dispose of objects
end try

BUT, what I want to be able to do is have multiple TRYs... one for the
delete, one for the update, one for the insert, (so I can customize the
thrown error message), then within the CATCH for each of those trys, do a
ROLLBACK. What I don't understand though, is that the FINALLY clause of the
TRY/CATCH is ALWAYS executed, so even if no error is encountered, my
sqlconnection would be closed in the first TRY. How is this supposed to be
handled? Should I close the connection/dispose of objects from within the
CATCH in every TRY, or will this be closed/disposed anyway because of the
thrown error?? Does that make sense?

Thanks a bunch,

D

Nov 20 '05 #1
4 2420
If you are calling three distinct types why not create three function one
for Update, Insert, Delete

Friend Function UpdateSQLStuff( ) as MyReturnResult
'do some sql stuff
End Function
Friend Function InsertSQLStuff( ) as MyReturnResult
'do some sql stuff
End Function
Friend Function DeleteSQLStuff( ) as MyReturnResult
'do some sql stuff
End Function

Or - You could add a paramater to your method/function

friend function DoSomeSQLStuff( byval SQLAction as String) as string
Try
'do some stuff
Catch ex as exception
Select Case SQLAction
Case Is = "Upate"
'handle update error
Case Is = "Delete"
'handle delete error
Case Is = "Insert"
'handle insert error
End Select
end try

In any sense, I wouldn't close your database connection without first
finishing your processing, if you know you are going to do an update, insert
and delete in every transaction then close it at the end, otherwise try to
seperate the logic in some way. Select Case? Your choice.
Hope that makes sense.
Jared

"Big D" <a@a.com> wrote in message
news:#9******** ******@TK2MSFTN GP09.phx.gbl...
Hi all,

I'm trying to understand the best way to use a try catch with a SQL
transaction. I have a number of sql statements that need to be run, such
as:

'open sqlConnection, get command object, etc.
myTrans.BeginTr ansaction()
'do a delete
'do a update
'do an insert
myTrans.Commit( )
'close connection/dispose of objects

However, I want to be able to roll it back so I do

myTrans.BeginTr ansaction()
Try
'do a delete
'do a update
'do an insert
catch ex as exception
myTrans.RollBac k()
throw new exception("ERRO R!",ex)
finally
'close connection/dispose of objects
end try

BUT, what I want to be able to do is have multiple TRYs... one for the
delete, one for the update, one for the insert, (so I can customize the
thrown error message), then within the CATCH for each of those trys, do a
ROLLBACK. What I don't understand though, is that the FINALLY clause of the TRY/CATCH is ALWAYS executed, so even if no error is encountered, my
sqlconnection would be closed in the first TRY. How is this supposed to be handled? Should I close the connection/dispose of objects from within the
CATCH in every TRY, or will this be closed/disposed anyway because of the
thrown error?? Does that make sense?

Thanks a bunch,

D

Nov 20 '05 #2
D,

If you are using SQL server then you could create named transactions. This
allow you to basically setup multiple roll back points. For instance in
your example you could roll back to the insert if the insert fails but
maintain the delete. The BOL has more detail.

Dan
Nov 20 '05 #3
"Big D" <a@a.com> wrote:
[...]
what I want to be able to do is have multiple TRYs...
one for the delete, one for the update, one for the
insert, (so I can customize the thrown error message),


You can customise your message even in a single try block.

try
{
strMsg = "error updating";
// ... update ...
strMsg = "error inserting";
// ... insert ...
}
catch
{
// display strMsg
}

P.

--
www.CL4.org
Nov 20 '05 #4
In addition to the conventional technique of nesting Try blocks, if you're
using VB.Net you can make use of the righteously cool 'When' feature in the
Catch block:

Create a state variable called, say Step. Increment Step after each
statement in the Try block, along the lines of the following:

try
step = 0
open the connection
step += 1
run the update
end try

and so on

Then write catch blocks like:

catch (ex as SqlException) When step = 1

catch (ex as Exception) When step = 1

catch (ex as SqlException) When step = 2

catch (ex as Exception) When step = 2

etc.

Between nested Try blocks, the When technique in VB.Net, and your own
understanding of what exception are likely to occur, I'd be surprised if you
couldn't figure out a sequence of steps that would handle the situation.

Regards,
Tom Dacon
Dacon Software Consulting

"Big D" <a@a.com> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
Hi all,

I'm trying to understand the best way to use a try catch with a SQL
transaction. I have a number of sql statements that need to be run, such
as:

'open sqlConnection, get command object, etc.
myTrans.BeginTr ansaction()
'do a delete
'do a update
'do an insert
myTrans.Commit( )
'close connection/dispose of objects

However, I want to be able to roll it back so I do

myTrans.BeginTr ansaction()
Try
'do a delete
'do a update
'do an insert
catch ex as exception
myTrans.RollBac k()
throw new exception("ERRO R!",ex)
finally
'close connection/dispose of objects
end try

BUT, what I want to be able to do is have multiple TRYs... one for the
delete, one for the update, one for the insert, (so I can customize the
thrown error message), then within the CATCH for each of those trys, do a
ROLLBACK. What I don't understand though, is that the FINALLY clause of the TRY/CATCH is ALWAYS executed, so even if no error is encountered, my
sqlconnection would be closed in the first TRY. How is this supposed to be handled? Should I close the connection/dispose of objects from within the
CATCH in every TRY, or will this be closed/disposed anyway because of the
thrown error?? Does that make sense?

Thanks a bunch,

D

Nov 20 '05 #5

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

Similar topics

31
14325
by: da Vinci | last post by:
OK, this has got to be a simple one and yet I cannot find the answer in my textbook. How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on? Basically: "Press any key to continue..." I beleive that I am looking for is something along the lines of a....
1
1210
by: rami | last post by:
I have some code which does following thing template<class X, unsigned ID = 0> struct SomeStruct { template<class X> static SomeStruct<X, ID + 1>& SomeFunc(); ... ... ... ...
9
2921
by: sk | last post by:
I have an applicaton in which I collect data for different parameters for a set of devices. The data are entered into a single table, each set of name, value pairs time-stamped and associated with a device. The definition of the table is as follows: CREATE TABLE devicedata ( device_id int NOT NULL REFERENCES devices(id), -- id in the device
9
1598
by: Daz | last post by:
Hello hello! I'm trying to finish off putting my design into HTML and I've come across a problem that I can't get my head around. I've got divs floating in two columns, but I'm having problems trying to put in images and floating them left or right. In safari it leaves a gap inbetween two of my divs and the image overlaps the gap, in IE it does the same unti you mouse over the hyperlink in the div, which then hides the gap and puts...
3
1543
by: Jesper Denmark | last post by:
Within the following construction switch (expression) { int i; i = GetArgs() //return 2 case constant-expression:
23
3259
by: Jason | last post by:
Hi, I was wondering if any could point me to an example or give me ideas on how to dynamically create a form based on a database table? So, I would have a table designed to tell my application to create certain textboxes, labels, and combo boxes? Any ideas would be appreciated. Thanks
1
3703
by: Rahul | last post by:
Hi Everybody I have some problem in my script. please help me. This is script file. I have one *.inq file. I want run this script in XML files. But this script errors shows . If u want i am attach this script files and inq files. I cant understand this error. Please suggest me. You can talk with my yahoo id b_sahoo1@yahoo.com. Now i am online. Plz....Plz..Plz...
9
1900
by: TF | last post by:
Hello all, I made a ASP.NET 2.0 site that shows possible "recipes" for paint colors stored in an access dbase. Basically, 1000 colors are stored with specific RGB values in separate columns. A user sees all the colors listed on the page with hyperlinks that open the "mixes" page. The mixes page goes through each record, compares it with all other records in a ratio up to "maxratio". If it finds a ratio that matches the redvalue of...
6
238
by: CD1 | last post by:
#include <string> This code won't compile. There is no variable called "foo2". :)
7
1840
by: sara | last post by:
I have a friend doing some pro-bono work for a non-profit that does job training for distressed kids under DCSS care. He asked me for code to do the following (he's using A2003). I can't find code in searches or on the MVP and tool sites I visited - though I might not understand that there is code that just needs adaptation. ALL help is appreciated. He wants a routine (that I'd put into a module) to do the following:
0
8234
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
8677
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
8335
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,...
0
7158
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
5563
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
4079
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
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1482
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.