Re: Can I throw a SqlException manually?

  • Thread starter Thread starter Jon Skeet [C# MVP]
  • Start date Start date
Nicky said:
I wrote a stored proc like that:
--------------------------------------------------------
declare @nTest as int
set @nTest = 100000
while @nTest > 0
begin
select * from MyTable
set @nTest = @nTest - 1
end
---------------------------------------------------------
And then in C#
try
{
SqlCommand cmd = new SqlCommand("TimeoutTest", m_dbConn);
cmd.CommandTimeout = 1;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}catch(SqlException ex)
{
.....
}
But even 1 min later, it does not throw a exception. It should throw
a time out exception 1 second later, is it right?

Yes, I suspect so - just to check, it hasn't actually finished
executing, has it? I would expect SQL Server to be able to work out
what's going on in the above and finish executing it very quickly :)
 
Jon Skeet said:
Unfortunately not - there are no public (or even protected)
constructors :(

I missed the rest of this thread, but just put a RaiseError in an SP.
 
Hi,

A better solution might be to define a new exception derived from
ApplicationException and throw that, but if you really want to raise an
exception from within a SQL script, you can use the raiserror statement.
Check books on line for details, but something along the lines of this
should work:

try
{
SqlCommand cmd = new SqlCommand("raiserror('text of exception', 16, 1)",
m_dbConn);
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string msg = ex.Message; // msg = "text of exception"
}




Nicky said:
I wrote a stored proc like that:
--------------------------------------------------------
declare @nTest as int
set @nTest = 100000
while @nTest > 0
begin
select * from MyTable
set @nTest = @nTest - 1
end
---------------------------------------------------------
And then in C#
try
{
SqlCommand cmd = new SqlCommand("TimeoutTest", m_dbConn);
cmd.CommandTimeout = 1;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
}catch(SqlException ex)
{
.....
}
But even 1 min later, it does not throw a exception. It should throw a
time out exception 1 second later, is it right?
 
Back
Top