Monday, June 12, 2006

How to Throw SqlException in C# manually?

It is not possible to throw SqlException maually in C# because SqlException class doesn't have any public constructor or even protected cosntructor.

But we can do that indirectly using the RAISEERROR function in SQLServer

For Example

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

The above code will throw an SqlExpcetion but the problem here is it takes a round trip time to database for executing the RAISEERROR function on DB Server.

2 Comments:

At 11:26 AM, Blogger Unknown said...

RAISERROR, not RAISEERROR :)

 
At 10:10 AM, Blogger Jen said...

This was great. Thank you!

 

Post a Comment

<< Home