473,396 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

ExecuteReader not throwing exception from T-SQL when using TRY-CATCH in stored proc

I am having an issue with SqlCommand class in C#. When I use ExecuteReader() on a T-SQL stored procedure that calls
RAISERROR() in a catch block the error does not get thrown in C#. I searched online and didn't find much but the one solution that I found that is pretty akward is to call NextResult() after done reading from tables.

Here is a simple example of what my SP is doing:
Expand|Select|Wrap|Line Numbers
  1. CREATE PROCEDURE [dbo].[test] 
  2. AS
  3. BEGIN
  4.  
  5.     DECLARE @ErrorMessage    NVARCHAR(4000);
  6.     DECLARE @ErrorSeverity    INT;
  7.     DECLARE @ErrorState        INT;
  8.  
  9.     BEGIN TRY
  10.  
  11.         select 1 / 0
  12.  
  13.     END TRY
  14.  
  15.  
  16.     BEGIN CATCH
  17.  
  18.         SET @ErrorMessage = ERROR_MESSAGE();
  19.         SET @ErrorSeverity = ERROR_SEVERITY();
  20.         SET @ErrorState = ERROR_STATE();
  21.         RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);
  22.  
  23.     END CATCH
  24. END
If you use ExecuteNonQuery() then the exception will come up but if you use ExecuteReader() it will not come up until you call NextResult().

Thanks,
Adam
Oct 8 '10 #1
6 6580
Curtis Rutland
3,256 Expert 2GB
It's because the error is part of a separate record set than the result.

Notice in SSMS when you do this query:



First it says (0 row(s) affected), then on the next line it shows the error.

If you look in the "Results" tab, you'll see there's actually an empty recordset as the first result:

Oct 8 '10 #2
I thought that but that doesnt make sense to me if I am calling it like this, also there is no result set I do not know what the 0 count is from


Expand|Select|Wrap|Line Numbers
  1.             try
  2.             {
  3.                 connection.Open();
  4.  
  5.                 SqlDataReader reader = command.ExecuteReader();
  6.  
  7.                 while (reader.Read())
  8.                 {
  9.                     Console.WriteLine("Line Read");
  10.                 }
  11.  
  12.                 Console.WriteLine("After Read");
  13.  
  14.                 // while (reader.NextResult()) ;
  15.  
  16.                 Console.WriteLine("No Exception");
  17.             }
  18.             catch (Exception exception)
  19.             {
  20.                 Console.WriteLine("Exception: {0}", exception);
  21.             }
  22.             finally
  23.             {
  24.                 if (connection != null)
  25.                     connection.Close();
  26.             }
Also I cannot view the images you posted
Oct 8 '10 #3
Curtis Rutland
3,256 Expert 2GB
I don't know what to tell you, other than that's just the way it is. The exception isn't in the first record set. It's in the second. The reason for that is because it's possible to return both records and an exception. It doesn't change the way it works because there are no rows, it just uses an empty record set.

You'll have to change the way you call it. First check to see if the record set is empty, then check to see if it has a second. If it does, an exception will be thrown, and you can catch and handle it.

As to the images, I don't know why you wouldn't be able to see them. They're hosted on imgur.com, perhaps that's blocked for you.
Oct 8 '10 #4
Bassem
344 100+
Hi, I'm not expert with SQL, but I've a theory - That I tested:

The row that appears in the result is because of the select in:
Expand|Select|Wrap|Line Numbers
  1. select 1 / 0
To avoid that, do the calculation then select the result like this:
Expand|Select|Wrap|Line Numbers
  1. BEGIN
  2.  
  3.     DECLARE @ErrorMessage    NVARCHAR(4000);
  4.     DECLARE @ErrorSeverity    INT;
  5.     DECLARE @ErrorState        INT;
  6.  
  7.     DECLARE @res int;
  8.  
  9.     BEGIN TRY
  10.  
  11.         --select 1 / 0
  12.         set @res = 1 / 0
  13.         select @res
  14.  
  15.     END TRY
  16.  
  17.  
  18.     BEGIN CATCH
  19.  
  20.         SET @ErrorMessage = ERROR_MESSAGE();
  21.         SET @ErrorSeverity = ERROR_SEVERITY();
  22.         SET @ErrorState = ERROR_STATE();
  23.         RAISERROR (@ErrorMessage,@ErrorSeverity,@ErrorState);
  24.  
  25.     END CATCH
  26. END
I hope this will help.
Oct 9 '10 #5
The bigger issue is that the exception is not getting registered. How do I make it so I will always have the exception thrown even if results are returned?
Oct 12 '10 #6
I have a stored procedure where I return a set of results and then do some updates. If the updates fail the C# SQLCommand.ExecuteReader() does not register the error. If I use NextResult() then the exception is trown like it was in the next set of results or something, though there is no other set. I can always call NextResult() and check or I can make sure the results are returned after the update, but is ther a safer way to flush out any possible errors that happen in stored procedure?

ex: This is the basic idea of what would happen with an error
Expand|Select|Wrap|Line Numbers
  1. SQL:
  2. SELECT 1;
  3. DECLARE @A int;
  4. SET @A = 1 / 0;
  5.  
  6. C#:
  7. SqlDataReader reader = command.ExecuteReader()
  8. while(reader.Read())
  9. {}
  10. // No exception yet
  11. // Now exception occurs with next line
  12. reader.NextResult();
  13.  
SQL Server 2008 - .Net 2.0
Oct 13 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Mark Oueis | last post by:
ArrayList arrayList = new ArrayList(); foreach (Blabla bla in Blablas) { arrayList.Add(Convert.ToInt32(blabla.something)); } so far this works great.. but now
9
by: John Fullman | last post by:
I have an application with a class that just doesn't seem to like destroying... I have a member that is stored on the heap and it is deleted in the destructor. When I run the app in debug...
5
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back...
2
by: Anup | last post by:
Hi Group, In my application I am using "Range Validator", validator is set for a textbox with range 1900 - 9999. and I am also using "Validation Summary" problem is when I run the application i...
2
by: naveen | last post by:
hai all I am working in a project in whihc i need to modify the dom of a webpage and reload the page with modified dom. so for this i thought of working with JSObject and with applet commnication...
40
by: Sek | last post by:
Is it appropriate to throw exception from a constructor? Thats the only way i could think of to denote the failure of constructor, wherein i am invoking couple of other classes to initialise the...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
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...
0
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...
0
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,...

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.