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:
RAISERROR, not RAISEERROR :)
This was great. Thank you!
Post a Comment
<< Home