473,573 Members | 2,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Another error handling question - best practice?

Hello,

I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module (note that this class module represents the business layer of code NOT the gui layer):

Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As SqlDataReader
' Declare the SQL data layer class
Dim oSQL As New SqlService(Conn ectionString)

' Add the parameters to the command object
oSQL.AddParamet er("@Parm1", SqlDbType.Small Int, 0, Parm1, ParameterDirect ion.Input)
oSQL.AddParamet er("@Parm2", SqlDbType.Small Int, 0, Parm2, ParameterDirect ion.Input)

' Run the stored procedure and return a datareader
Return oSQL.RunProcRea der("SQLStoredP rocedureName")
End Function

which is calling the following library function (data access layer of code) which can/could throw an exception (which I believe already has valid error handling in it):

Public Function RunProcReader(B yVal sProcName As String) As SqlDataReader
' Check to make sure we have all the data necessary for a connection
If Not IsValidConnecti onString() Then
Throw New InvalidConnecti onException("In valid SQL connection string: " & ConnectionStrin g)
End If

Dim dr As SqlDataReader '//--- Create a new sqlDataReader
Dim oCmd As SqlCommand = New SqlCommand '//--- Create a new SqlCommand
Dim oCn As SqlConnection = Nothing '//--- Declare the SqlConnection
Dim oSqlParameter As SqlParameter = Nothing '//--- Declare a SqlParameter
Dim oP As Parameter = Nothing '//--- Declare a Parameter

'Get an enumerator for the parameter array list
Dim oEnumerator As IEnumerator = m_oParmList.Get Enumerator()

Try
'Prepare connection to the database
oCn = Connect()

With oCmd
.Connection = oCn
.CommandText = sProcName
.CommandType = CommandType.Sto redProcedure
End With

'Add the parameters to the command
AddParameters(o Enumerator, oCmd)

' Open the connection
oCn.Open()

' Execute the datareader, and close the connection
dr = oCmd.ExecuteRea der(CommandBeha vior.CloseConne ction)
Catch ex As Exception
Throw
Finally
Disconnect(oCn)
End Try

'Get the output parameter values if there were no errors
GetOutputParame terValues(oCmd)

'Return the DataReader
Return dr
End Function

How would we add error handling into the Test function above to be able to gracefully handle the errors encountered in the data access layer (RunProcReader) AND to gracefully send the error back to the gui calling program? Do we just simply enclose everything in a try catch, and then also enclose the call to the Test function (from the GUI layer) within a try catch block so that if an error is encountered we can gracefully handle the presentation?

Anyone care to provide us with ideas as to what you are doing in similar circumstances?

Jim
Nov 20 '05 #1
4 7602
Hi James,

Methods in your business layer should only be catching errors if they can
deal with the error internally (not very common) or they can add valuable
information to they error on it's way up to the UI layer. For example,
RunProcReader should not have a catch block (just a try...finally) because
it is not adding any information that the handling method can use, you are
just adding extra overhead without adding any extra value.

What you could do instead is have RunProcReader catch the exception and then
throw a custom exception that has properties like the name of the stored
procedure and the connection string. If you do this make sure to include the
original exception as the InnerException.

There's a good chapter on exception handling in Jeffrey Richter's "Applied
Microsoft.NET Framework Programming" (Microsoft Press) .

Hope this helps.

--
Rob Windsor
G6 Consulting
Toronto, Canada

"James Radke" <jr*****@wi.rr. com> wrote in message
news:e1******** ******@TK2MSFTN GP10.phx.gbl...
Hello,

I am looking for guidance on best practices to incorporate effective and
complete error handling in an application written in VB.NET. If I have the
following function in a class module (note that this class module represents
the business layer of code NOT the gui layer):

Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As
SqlDataReader
' Declare the SQL data layer class
Dim oSQL As New SqlService(Conn ectionString)

' Add the parameters to the command object
oSQL.AddParamet er("@Parm1", SqlDbType.Small Int, 0, Parm1,
ParameterDirect ion.Input)
oSQL.AddParamet er("@Parm2", SqlDbType.Small Int, 0, Parm2,
ParameterDirect ion.Input)

' Run the stored procedure and return a datareader
Return oSQL.RunProcRea der("SQLStoredP rocedureName")
End Function

which is calling the following library function (data access layer of code)
which can/could throw an exception (which I believe already has valid error
handling in it):

Public Function RunProcReader(B yVal sProcName As String) As
SqlDataReader
' Check to make sure we have all the data necessary for a
connection
If Not IsValidConnecti onString() Then
Throw New InvalidConnecti onException("In valid SQL connection
string: " & ConnectionStrin g)
End If

Dim dr As SqlDataReader '//---
Create a new sqlDataReader
Dim oCmd As SqlCommand = New SqlCommand '//---
Create a new SqlCommand
Dim oCn As SqlConnection = Nothing '//---
Declare the SqlConnection
Dim oSqlParameter As SqlParameter = Nothing '//---
Declare a SqlParameter
Dim oP As Parameter = Nothing '//---
Declare a Parameter

'Get an enumerator for the parameter array list
Dim oEnumerator As IEnumerator = m_oParmList.Get Enumerator()

Try
'Prepare connection to the database
oCn = Connect()

With oCmd
.Connection = oCn
.CommandText = sProcName
.CommandType = CommandType.Sto redProcedure
End With

'Add the parameters to the command
AddParameters(o Enumerator, oCmd)

' Open the connection
oCn.Open()

' Execute the datareader, and close the connection
dr = oCmd.ExecuteRea der(CommandBeha vior.CloseConne ction)
Catch ex As Exception
Throw
Finally
Disconnect(oCn)
End Try

'Get the output parameter values if there were no errors
GetOutputParame terValues(oCmd)

'Return the DataReader
Return dr
End Function

How would we add error handling into the Test function above to be able to
gracefully handle the errors encountered in the data access layer
(RunProcReader) AND to gracefully send the error back to the gui calling
program? Do we just simply enclose everything in a try catch, and then also
enclose the call to the Test function (from the GUI layer) within a try
catch block so that if an error is encountered we can gracefully handle the
presentation?

Anyone care to provide us with ideas as to what you are doing in similar
circumstances?

Jim
Nov 20 '05 #2
Rob,

If you only use the Try.. Finally without a catch wouldn't my program
"abend" without the catch as soon as a problem is encountered?

Jim
"Rob Windsor" <rw******@NO.MO RE.SPAM.bigfoot .com> wrote in message
news:OD******** ******@TK2MSFTN GP10.phx.gbl...
Hi James,

Methods in your business layer should only be catching errors if they can
deal with the error internally (not very common) or they can add valuable
information to they error on it's way up to the UI layer. For example,
RunProcReader should not have a catch block (just a try...finally) because
it is not adding any information that the handling method can use, you are
just adding extra overhead without adding any extra value.

What you could do instead is have RunProcReader catch the exception and then throw a custom exception that has properties like the name of the stored
procedure and the connection string. If you do this make sure to include the original exception as the InnerException.

There's a good chapter on exception handling in Jeffrey Richter's "Applied
Microsoft.NET Framework Programming" (Microsoft Press) .

Hope this helps.

--
Rob Windsor
G6 Consulting
Toronto, Canada

"James Radke" <jr*****@wi.rr. com> wrote in message
news:e1******** ******@TK2MSFTN GP10.phx.gbl...
Hello,

I am looking for guidance on best practices to incorporate effective and
complete error handling in an application written in VB.NET. If I have the following function in a class module (note that this class module represents the business layer of code NOT the gui layer):

Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As SqlDataReader
' Declare the SQL data layer class
Dim oSQL As New SqlService(Conn ectionString)

' Add the parameters to the command object
oSQL.AddParamet er("@Parm1", SqlDbType.Small Int, 0, Parm1,
ParameterDirect ion.Input)
oSQL.AddParamet er("@Parm2", SqlDbType.Small Int, 0, Parm2,
ParameterDirect ion.Input)

' Run the stored procedure and return a datareader
Return oSQL.RunProcRea der("SQLStoredP rocedureName")
End Function

which is calling the following library function (data access layer of code) which can/could throw an exception (which I believe already has valid error handling in it):

Public Function RunProcReader(B yVal sProcName As String) As
SqlDataReader
' Check to make sure we have all the data necessary for a
connection
If Not IsValidConnecti onString() Then
Throw New InvalidConnecti onException("In valid SQL connection string: " & ConnectionStrin g)
End If

Dim dr As SqlDataReader '//---
Create a new sqlDataReader
Dim oCmd As SqlCommand = New SqlCommand '//---
Create a new SqlCommand
Dim oCn As SqlConnection = Nothing '//---
Declare the SqlConnection
Dim oSqlParameter As SqlParameter = Nothing '//---
Declare a SqlParameter
Dim oP As Parameter = Nothing '//---
Declare a Parameter

'Get an enumerator for the parameter array list
Dim oEnumerator As IEnumerator = m_oParmList.Get Enumerator()

Try
'Prepare connection to the database
oCn = Connect()

With oCmd
.Connection = oCn
.CommandText = sProcName
.CommandType = CommandType.Sto redProcedure
End With

'Add the parameters to the command
AddParameters(o Enumerator, oCmd)

' Open the connection
oCn.Open()

' Execute the datareader, and close the connection
dr = oCmd.ExecuteRea der(CommandBeha vior.CloseConne ction)
Catch ex As Exception
Throw
Finally
Disconnect(oCn)
End Try

'Get the output parameter values if there were no errors
GetOutputParame terValues(oCmd)

'Return the DataReader
Return dr
End Function

How would we add error handling into the Test function above to be able to
gracefully handle the errors encountered in the data access layer
(RunProcReader) AND to gracefully send the error back to the gui calling
program? Do we just simply enclose everything in a try catch, and then also enclose the call to the Test function (from the GUI layer) within a try
catch block so that if an error is encountered we can gracefully handle the presentation?

Anyone care to provide us with ideas as to what you are doing in similar
circumstances?

Jim

Nov 20 '05 #3
"James Radke" <jr*****@wi.rr. com> wrote in
news:uC******** *****@TK2MSFTNG P10.phx.gbl:
Rob,

If you only use the Try.. Finally without a catch wouldn't my program
"abend" without the catch as soon as a problem is encountered?

No, it should be caught by an exception handler higher up the call stack.
If there is no exception handler higher up, then it would probably "abend"

Chris
Nov 20 '05 #4

No. When an exception occurs .NET will walk the call stack until it finds
the first method that has an enclosing catch block. Because many of your
business objects will not be catching errors but still need to ensure
resources are released you will see about a 10-1 ratio of try...finally to
try...catch blocks. In the UI the ratio of try...catch is considerably
higher.

I took a quick look and I found this article at the link below which
discusses error handling in a little bit more detail. I'm sure there are
other free resources out there as well.

http://msdn.microsoft.com/msdnmag/is...s/default.aspx

Rob

"James Radke" <jr*****@wi.rr. com> wrote in message
news:uC******** *****@TK2MSFTNG P10.phx.gbl...
Rob,

If you only use the Try.. Finally without a catch wouldn't my program
"abend" without the catch as soon as a problem is encountered?

Jim
"Rob Windsor" <rw******@NO.MO RE.SPAM.bigfoot .com> wrote in message
news:OD******** ******@TK2MSFTN GP10.phx.gbl...
Hi James,

Methods in your business layer should only be catching errors if they can deal with the error internally (not very common) or they can add valuable information to they error on it's way up to the UI layer. For example,
RunProcReader should not have a catch block (just a try...finally) because it is not adding any information that the handling method can use, you are just adding extra overhead without adding any extra value.

What you could do instead is have RunProcReader catch the exception and then
throw a custom exception that has properties like the name of the stored
procedure and the connection string. If you do this make sure to include

the
original exception as the InnerException.

There's a good chapter on exception handling in Jeffrey Richter's "Applied Microsoft.NET Framework Programming" (Microsoft Press) .

Hope this helps.

--
Rob Windsor
G6 Consulting
Toronto, Canada

"James Radke" <jr*****@wi.rr. com> wrote in message
news:e1******** ******@TK2MSFTN GP10.phx.gbl...
Hello,

I am looking for guidance on best practices to incorporate effective and
complete error handling in an application written in VB.NET. If I have

the
following function in a class module (note that this class module

represents
the business layer of code NOT the gui layer):

Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As
SqlDataReader
' Declare the SQL data layer class
Dim oSQL As New SqlService(Conn ectionString)

' Add the parameters to the command object
oSQL.AddParamet er("@Parm1", SqlDbType.Small Int, 0, Parm1,
ParameterDirect ion.Input)
oSQL.AddParamet er("@Parm2", SqlDbType.Small Int, 0, Parm2,
ParameterDirect ion.Input)

' Run the stored procedure and return a datareader
Return oSQL.RunProcRea der("SQLStoredP rocedureName")
End Function

which is calling the following library function (data access layer of

code)
which can/could throw an exception (which I believe already has valid

error
handling in it):

Public Function RunProcReader(B yVal sProcName As String) As
SqlDataReader
' Check to make sure we have all the data necessary for a
connection
If Not IsValidConnecti onString() Then
Throw New InvalidConnecti onException("In valid SQL

connection
string: " & ConnectionStrin g)
End If

Dim dr As SqlDataReader '//---
Create a new sqlDataReader
Dim oCmd As SqlCommand = New SqlCommand '//---
Create a new SqlCommand
Dim oCn As SqlConnection = Nothing '//---
Declare the SqlConnection
Dim oSqlParameter As SqlParameter = Nothing '//---
Declare a SqlParameter
Dim oP As Parameter = Nothing '//---
Declare a Parameter

'Get an enumerator for the parameter array list
Dim oEnumerator As IEnumerator = m_oParmList.Get Enumerator()

Try
'Prepare connection to the database
oCn = Connect()

With oCmd
.Connection = oCn
.CommandText = sProcName
.CommandType = CommandType.Sto redProcedure
End With

'Add the parameters to the command
AddParameters(o Enumerator, oCmd)

' Open the connection
oCn.Open()

' Execute the datareader, and close the connection
dr = oCmd.ExecuteRea der(CommandBeha vior.CloseConne ction)
Catch ex As Exception
Throw
Finally
Disconnect(oCn)
End Try

'Get the output parameter values if there were no errors
GetOutputParame terValues(oCmd)

'Return the DataReader
Return dr
End Function

How would we add error handling into the Test function above to be able

to gracefully handle the errors encountered in the data access layer
(RunProcReader) AND to gracefully send the error back to the gui calling
program? Do we just simply enclose everything in a try catch, and then

also
enclose the call to the Test function (from the GUI layer) within a try
catch block so that if an error is encountered we can gracefully handle

the
presentation?

Anyone care to provide us with ideas as to what you are doing in similar
circumstances?

Jim


Nov 20 '05 #5

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

Similar topics

2
2029
by: aaj | last post by:
Hi all I have an automated application, that runs in the middle of the night. If certain 'non system' errors occur (things like malformed files, missing files etc..), I send an automatic Email and write a record to the database. This is handled in a class. When these errors occur, once Emailed and written I want to just end the App,...
9
2613
by: Mark Twombley | last post by:
Hi, I'm just getting back into C++ and had a question about the best practice for assigning error numbers. I have been working in VB for sometime now and there you would start assigning error number at vbObjectError + count. Is there a similar practice in C++ or is it just coder preference. Thanks -- Mark Twombley
1
8038
by: annie | last post by:
Hi all, I have recently ported my Access 2000 app to SQL Server, keeping the Access client as the front end using linked tables. I am also using triggers on my SQL tables to trap orphan records and validate added data. My question is..
4
2519
by: aaj | last post by:
Hi all I have an automated application, that runs in the middle of the night. If certain 'non system' errors occur (things like malformed files, missing files etc..), I send an automatic Email and write a record to the database. This is handled in a class. When these errors occur, once Emailed and written I want to just end the App,...
4
1982
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...
3
2841
by: Stefan Johansson | last post by:
Hi all I'am moving from Visual Foxpro and have a question regarding "best practice" error handling in vb .net. In VFP I have always used a "central" error handling object in order to have a easy and reusable way of handling all errors in a program. The VB 6 coding examples I have seen there has always been error handling code in each...
7
2336
by: Garth Wells | last post by:
I'm trying to create a DAL and am wondering what's the proper way to handle errors in this Insert method. public string Insert() { Database db = DatabaseFactory.CreateDatabase(); string sqlCommand = "pr_testx"; DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
5
1729
by: csgraham74 | last post by:
Hi guys, Basically i have been developing in dotnet for a couple of years but ive had a few issues in regards to error handling. For example - I have a class that i call passing in a stored procedure and connection string as a path. My method returns a dataset. In my SP i have an output parameter which tells me whether the SP select is...
0
1027
by: acnx | last post by:
I have an ntier application. I am trying to determine what is the best practice for handing errors in a datagrid. My datagrids are able to add, update and delete data. I am using a objectdatasource to access a proxy which calls a remote business object. The objectdatasource uses a custom class to pass the data to the business layer. The...
0
8027
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. ...
0
8202
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7788
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...
0
6421
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...
1
5594
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...
0
5292
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...
0
3733
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...
0
3733
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1041
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...

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.