using try-catch-finally to get DB errors

Lets say I'm using the following code to do something with database, how do I get any database error and display it as my own error message?

1    // Declare objects
2                SqlConnection conn;
3                SqlCommand categoryComm;
4                SqlCommand subjectComm;
5                SqlDataReader reader;
6    
7                // Read connection string from web.Config
8                string connectionString = ConfigurationManager.ConnectionStrings["Dorknozzle"].ConnectionString;
9    
10               // Initialise the connection
11               conn = new SqlConnection(connectionString);
12   
13               // Create command to read the help desk categories
14               categoryComm = new SqlCommand(
15                   "SELECT CategoryID, Category FROM HelpDeskCategories", conn);
16   
17               // Create comman to read the help desk subjects
18               subjectComm = new SqlCommand(
19                   "SELECT SubjectID, Subject FROM HelpDeskSubjects", conn);
20   
21               try
22               {
23                   // Open the connection
24                   conn.Open();
25   
26                   // Execute the category command
27                   reader = categoryComm.ExecuteReader();
28   
29                   // Populate the list of categories
30                   categoryList.DataSource = reader;
31                   categoryList.DataValueField = "CategoryID";
32                   categoryList.DataTextField = "Category";
33                   categoryList.DataBind();
34   
35                   // Close the reader
36                   reader.Close();
37   
38                   // Execute the command
39                   reader = subjectComm.ExecuteReader();
40   
41                   // Populate the list of subjects
42                   subjectList.DataSource = reader;
43                   subjectList.DataValueField = "SubjectID";
44                   subjectList.DataTextField = "Subject";
45                   subjectList.DataBind();
46   
47                   // Close the reader
48                   reader.Close();
49               }
50               finally
51               {
52                   // Close the connection
53                   conn.Close();
54               }
55           }
56   
57       }
58       protected void submitButton_Click(object sender, EventArgs e)
59       {
60           if (Page.IsValid)
61           {
62               // Define data objects
63               SqlConnection conn;
64               SqlCommand comm;
65   
66               // Read the connection string from web.Config
67               string connectionString = ConfigurationManager.ConnectionStrings["Dorknozzle"].ConnectionString;
68   
69               // Initialise connection
70               conn = new SqlConnection(connectionString);
71   
72               // Create new command
73               comm = new SqlCommand(
74                   "INSERT INTO HelpDesk (EmployeeID, StationNumber, " +
75                   "CategoryID, SubjectID, Description, StatusID) " +
76                   "VALUES (@EmployeeID, @StationNumber, @CategoryID, " +
77                   "@SubjectID, @Description, @StatusID)", conn);
78   
79               // Add command parameters
80               comm.Parameters.Add("@EmployeeID", System.Data.SqlDbType.Int);
81               comm.Parameters["@EmployeeID"].Value = 5;
82               comm.Parameters.Add("@StationNumber", System.Data.SqlDbType.Int);
83               comm.Parameters["@StationNumber"].Value = stationTextBox.Text;
84               comm.Parameters.Add("@CategoryID", System.Data.SqlDbType.Int);
85               comm.Parameters["@CategoryID"].Value = categoryList.SelectedItem.Value;
86               comm.Parameters.Add("@SubjectID", System.Data.SqlDbType.Int);
87               comm.Parameters["@SubjectID"].Value = subjectList.SelectedItem.Value;
88               comm.Parameters.Add("@Description", System.Data.SqlDbType.NVarChar, 50);
89               comm.Parameters["@Description"].Value = descriptionTextBox.Text;
90               comm.Parameters.Add("@StatusID", System.Data.SqlDbType.Int);
91               comm.Parameters["@StatusID"].Value = 1;
92   
93               // Enclose database code in try-catch-finally
94               try
95               {
96                   // Open the connection
97                   conn.Open();
98   
99                   // Execute the command
100                  comm.ExecuteNonQuery();
101  
102                  // Reload page if the query executed successfully
103                  Response.Redirect("Helpdesk.aspx");
104              }
105              catch
106              {
107                  // Display error message
108                  dbErrorMessage.Text =
109                      "Error submitting the help desk request! Please " +
110                      "try later, and/or change the entered data!";
111              }
112              finally
113              {
114                  // Close the connection
115                  conn.Close();
116              }
 
Alive with Technology Ltd
0
littlened
8/21/2007 10:32:42 AM
asp.net.object-datasource 16182 articles. 0 followers. Follow

1 Replies
632 Views

Similar Articles

[PageSpeed] 7
Get it on Google Play
Get it on Apple App Store

I think this may be what you're looking for.  This is a modified piece of code I used for a file upload where some of the fields in the spreadsheet uploaded may already be in the database (hence the 2627 part).  The first catch block displays a specific error that I know occurs frequently when the user makes a mistake, and the second one is for anything else that may come up except a primary key violation, which is ignored.

 

1    Catch notnewfile As System.InvalidOperationException
2    Label4.Text = "An error occurred during the process."
3    Exit Sub
4    Catch ex As System.Data.SqlClient.SqlException
5    If ex.Number <> 2627 Then
6    Label4.Text = "An error occurred during the process. The database may be unavailable. If this problem persists please contact your network administrator”
7    End If
8    End Try
 

 


Life is like a box of chocolates. A cheap, thoughtless, perfunctory gift that nobody ever asks for. Unreturnable because all you get back is another box of chocolates. So you're stuck with this undefinable whipped mint crap that you mindlessly wolf down when there's nothing else left to eat. Sure, once in a while there's a Peanut Butter Cup or an English Toffee. But they're gone too fast and the taste is... fleeting. So you end up with nothing but broken bits filled with hardened jelly and teeth-shattering nuts. And if you're desperate enough to eat those, all you got left is an empty box... filled with useless brown paper wrappers.
0
Gipionocheiyort
8/21/2007 1:36:33 PM
Reply:

Similar Artilces:

I get this error when i use object datasource
This is the first time i am using object datasource , I am getting an error saying Procedure or Function 'GeteGroupExceptionalByResource' expects parameter '@ResourceName', which was not supplied.   I tried several times to solve the error , but i couldnt able to , I tried debugging several times,but couldnt able to solve the error .For many attemps i get the same above error ,pls advice me how to solve this error   Thanks You have to pass the value for the paramneter @ResourceName through your coding or in Properties window depanding upon your project PROC...

skipping null object reference error using try catch
win xp\ pb 9 hi. I am using oleobjects to load pdf,word files and analyzing the text. if a doc or pdf has no data, its throwing me an error "R002 null object reference" for that particular page. I am new to pb. can any one suggest me how to use 'try catch' to skip this pb error. A sample code to recognise null object reference and allow the application not to exit and do some operations on encountering that error should do. thanks in advance. You can use "IF isValid(<object reference>)" to check if the object reference is null. -- Reg...

try catch finally
Hi, Can anyone explain to me why the first example does not work (I get an CS0165: Use of unassigned local variable 'dbReader' error) but the second one does? Cheers, Daniel Example 1private void login_user() { SqlConnection dbCon; SqlCommand dbCom; SqlDataReader dbReader; String strSQL; try { dbCon = new SqlConnection("Data Source=WEBSQL;Initial Catalog=hr-app;User Id=admin0;Password=w3b-s1te;"); dbCon.Open(); dbCom = dbCon.CreateCommand(); dbCom.Parameters.Add(new SqlParameter("@username", System.Dat...

What if Finally throws an error in try-catch-finally?
can anyone tell me What if Finally throws an error in try-catch-finally? CheersBinowww.codepal.co.inPlease Mark as Answer if you find the post useful. It'll throw an exception - being in the finally block doesn't exclude your code from throwing exceptions.You can put another try/catch block inside the finally block if you want to trap exceptions there.  Then the exception that is generated in the Finally block will propagate up the call stack until a Catch block is found For example Sub Main()  Try    Foo()  Catch    Console.Wri...

catching DB exception in powerscript using try---catch
I have the below piece of code & I know the retrieve stmnt is failing. Verifying that by getting a -1 in ll_ret var. For some reason, I am not able to catch the error description in the CATCH block. can i catch a DB errors & if so how can i do it? I am able to catch Runtime errors in PB using the "RunTimeError" object. Pl. help AR ----------------------------------------- long ll_ret try of_connect(anv_callback) ids_report = CREATE datastore ids_report.setFullState(anv_callback.iblb_data) ids_report.setTransObject(itr_trans) ll_ret = ids_report.retrieve...

"activex component can t create object" error when trying to use .net dll in VB6
Hi everyone!I've writen a small .net class library to communicate with my web service to fetch some data from the database, etc,I have selected  "register for com interop" option, I added the reference to the vb6 project and everything works fine,but, when I deploy my whole project in another pc, I get  "activex component can t create object" error!I use a custom setup (using Inno setup) and register the type library file (tlb),which is copied to the vb6 exe's directory,I searched the registry and found the same registration entries in both pcs,so, what&...

trying to get a simple url page using lwp but getting a 500 error
I am using the .bat file which comes with LWP called lwp-download.bat. When I type: lwp-download http:\\oracledev1.traco.com:8001 the reponse I get is: lwp-download: 500 Can't connect to :80 (Bad hostname ' ') I this this error message no matter what I try, and being brand new to LWP and rather new to Perl, I have no idea what to try next.... Thanks for any help I receive in advance!!!! your url is not correct. it should be http:// and not http:\\ ----- Original Message ----- From: "Ken Soenen" <Ken.Soenen@TRACO.COM> To: <libwww@perl.org...

Error when trying to use website admin tool using .net 3.5
When I use either the icon or the website menu to get to the configuration tool - it simply never shows up. the localhost for my site starts(as tho i had pressed debug), and then another localhost starts for the web config. Neither of these starts trigger a browser to open. if I click the localhost and go to them manually, the page functions fine, and the config reports "An error was encountered. Please return to the previous page and try again." Also of interest, I use Firebug (a javascript plugin for firefox) and noted this error being thrown : [Exception... "'Abor...

try ... catch an "Error accessing external object property" error
Hi, I've coded a function of a service object which is called in the rButtonDown event of datawindows. The argument is the datawindowobject dwo from the event arguments. The function have to check for the band property of the dwo: ls_band = dwo.band If the user rightClicks in an empty area of the datawindow, a system error arises: Error accessing external object property band at line 11 in function uf_rbuttondown of object u_nv_fs_dwsrvc. So I want to avoid this using a try .. catch ... finally block: try ls_band = dwo.band catch(exeption le_all) ls_b...

Getting error when saving to my db. Trying to limit number of character saved to db.
I am using the following INSERT command in my Source.  The 'notes' field in my DB is VarChar 7000 characters.  I am trying to limit the amout of characters that can be saved to 7000 characters to my db. InsertCommand="INSERT INTO [info] ([class_name], [info_date], LEFT([notes], 7000)) VALUES (@class_name, @info_date, @notes)"> If I try to submit more than 7000 characters I get the following error message. "An error occured while entering this record. Please verify you have entered data in the correct format." I thought that the Left 7000 would limit it to the fir...

used a c#.net to vb.net converter and am now getting a syntax error.
ok I used a cool utility at http://www.kamalpatel.net/ConvertCSharp2VB.aspx to convert some c#.net to vb.net and it spit out a bunch of code which almost works but I am getting a syntax error on this line Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) I tried it that way and also like Imports (StreamReader sr = Shadows Function)() As StreamReader(objResponse.GetResponseStream()) but either way gave the same error Compiler Error Message: BC30035: Syntax error. Source Error: Line 26: Line ...

When trying to connect to a datasource I get error server error in '/Test Data' Application
An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Source Error: Line 29: { Line 30: // fill teh data set. Line 31: oleDbDataAdapter1.Fill(dataSet21); Line 32: // Update teh DataGrid Line 33: DataGrid1.DataBind();David StoutSystems ProgrammerRegency Homesragbrai65@yahoo.com could you post your code in particular the connection string. using System; using System.Collections; using System.ComponentModel; using System.Data; u...

using try...catch...finally
Where is the best place to put my response.redirect statement when using try...catch...finally? Here is part of my code for inserting a record. If I place the respone.redirect in the try portion will the connection still close? When I place the response.redirect in the finally clause I never see an error when it occurs. Or should I place the response.redirect outside of the try...catch... finally clause. cmd = new OracleCommand(sbInsert.ToString(), cnYes32); cnYes32.Open(); try { cmd.ExecuteNonQuery(); Response.Redirect("default.aspx"); } catch ...

When using a sqldataadapter in VS 2005 I get the following error at runtime. Object reference not set to an instance of an object
Help! I have posted this before and I had hoped that the VS2005 SP1 would help my problem. It didn't. My code is shown below. I have dropped a sqlconnection, sqldataadapter and a strongly-typed dataset from the toolbox onto the component designer for my page and written my code. It compiles without any errors but at runtine I receive the system error "Object reference not set to an instance of an object." The error occurs at the first line where the sqldataadapter is mentioned. I have shufflled the code and the error still occurs at first mention of the dataadapter. I have set parameters to ...

Web resources about - using try-catch-finally to get DB errors - asp.net.object-datasource

Resources last updated: 12/8/2015 5:36:55 AM