c#捕获不了 raiseerror

在项目中调用存储过程,设置有raiseerror但是并没有抛出异常。

SQL代码如下:

ALTER PROCEDURE sp_test	
AS
BEGIN
     -----------------制造异常
     BEGIN TRY
     SELECT 1/0;
     -----------------捕获异常
     END TRY
     BEGIN CATCH
		PRINT 'b4catch'
        RAISERROR('Rais Error1', 16, 1) WITH NOWAIT
        PRINT 'afcatch'
     END CATCH
END
GO

  C#代码如果参照http://blog.csdn.net/xinchimaker/article/details/6100821 ,可以正常捕获异常的。

但是在项目中却没有捕获到,查看了源码发现调用的存储过程有问题:

string strcon = "server=.;database=test;uid=sa;password=123456";
            DataTable dt = new DataTable();
            using(SqlConnection sqlcon =new SqlConnection(strcon))
            {
                string strcmd = "sp_test";
                SqlCommand sqlcmd = new SqlCommand(strcmd, sqlcon);
                sqlcmd.CommandType = System.Data.CommandType.StoredProcedure;
                SqlDataAdapter adpter = new SqlDataAdapter() { SelectCommand=sqlcmd};
                adpter.Fill(dt);
            }

  最后定位发现是标红地方的原因,把SelectCommand 修改为UpdateCommand 。问题解决。

原文地址:https://www.cnblogs.com/gg_lihui/p/8358610.html